botsFeishuProvider.test.ts 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import type { BotConfig, BotOutboundMessage } from "@zcode/shared";
  3. const sdkLoaded = vi.hoisted(() => vi.fn());
  4. vi.mock("@larksuiteoapi/node-sdk", () => {
  5. sdkLoaded();
  6. return {};
  7. });
  8. import { TopicHistoryPermissionError } from "../src/bots/topicHistory.js";
  9. import {
  10. countFeishuCardTaggedElements,
  11. createFeishuBotProvider,
  12. createFeishuWebSocketEventHandlers,
  13. splitFeishuStreamingCardStates,
  14. } from "../src/bots/providers/feishuProvider.js";
  15. afterEach(() => {
  16. vi.useRealTimers();
  17. vi.unstubAllGlobals();
  18. // 卡片与 HTTP 路径不应为未启用的长连接加载整份 SDK。
  19. expect(sdkLoaded).not.toHaveBeenCalled();
  20. });
  21. function createFeishuBot(overrides: Partial<BotConfig> = {}): BotConfig {
  22. return {
  23. id: "feishu-1",
  24. name: "Feishu",
  25. provider: "feishu" as const,
  26. enabled: true,
  27. credentialRef: "app-secret",
  28. feishuAppId: "cli_xxx",
  29. allowedWorkspaces: ["*"],
  30. allowedCommands: {
  31. status: true,
  32. new: true,
  33. workspace: true,
  34. model: true,
  35. thoughtLevel: true,
  36. sandboxMode: true,
  37. approvalPolicy: true,
  38. reply: true,
  39. },
  40. currentOptions: {},
  41. replyMode: "assistant_changes" as const,
  42. ...overrides,
  43. };
  44. }
  45. function parseFeishuCardContent(content: string | undefined): Record<string, unknown> {
  46. return JSON.parse(String(content)) as Record<string, unknown>;
  47. }
  48. describe("feishu bot provider", () => {
  49. it("sends ordered native body mentions, escapes typed markup and deduplicates the header", async () => {
  50. const requests: Array<Record<string, unknown>> = [];
  51. vi.stubGlobal(
  52. "fetch",
  53. vi.fn(async (url: string, init?: RequestInit) => {
  54. if (url.includes("tenant_access_token"))
  55. return Response.json({ code: 0, tenant_access_token: "native-parts", expire: 3600 });
  56. requests.push(JSON.parse(String(init?.body)));
  57. return Response.json({ code: 0, data: { message_id: "om_native" } });
  58. }),
  59. );
  60. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  61. const parts = [
  62. { type: "text" as const, text: "请 " },
  63. {
  64. type: "channelMention" as const,
  65. refId: "m1",
  66. name: "Ryan Bot",
  67. channel: "feishu" as const,
  68. targetId: "ou_ryan",
  69. idType: "open_id" as const,
  70. entityType: "unknown" as const,
  71. },
  72. { type: "text" as const, text: " 确认 <at id=all></at>" },
  73. ];
  74. const message: BotOutboundMessage = {
  75. botId: "feishu-1",
  76. provider: "feishu",
  77. providerUserId: "oc_group",
  78. replyToMessageId: "om_input",
  79. threadId: "omt_topic",
  80. text: "请 @Ryan Bot 确认 <at id=all></at>",
  81. contentParts: parts,
  82. mentionedUserIds: ["ou_ryan"],
  83. deliveryId: "native-delivery",
  84. };
  85. expect(await provider.send(createFeishuBot({ feishuAppId: "native-parts" }), message)).toEqual({
  86. providerMessageId: "om_native",
  87. });
  88. const card = JSON.parse(String(requests[0]?.content));
  89. expect(card.body.elements).toEqual([
  90. { tag: "markdown", content: "请 <at id=ou_ryan></at> 确认 &lt;at id=all&gt;&lt;/at&gt;" },
  91. ]);
  92. expect(requests[0]?.reply_in_thread).toBe(true);
  93. await expect(
  94. provider.send(createFeishuBot(), { ...message, text: "different" }),
  95. ).rejects.toThrow("Invalid native");
  96. expect(requests).toHaveLength(1);
  97. });
  98. it.each([false, true])(
  99. "quotes group replies and mentions only the first text segment (selection=%s)",
  100. async (selection) => {
  101. const requests: Array<{ url: string; body: Record<string, unknown> }> = [];
  102. vi.stubGlobal(
  103. "fetch",
  104. vi.fn(async (url: string, init?: RequestInit) => {
  105. if (url.includes("tenant_access_token"))
  106. return Response.json({ code: 0, tenant_access_token: "mention-token", expire: 3600 });
  107. requests.push({ url, body: JSON.parse(String(init?.body)) });
  108. return Response.json({ code: 0, data: { message_id: "om_result" } });
  109. }),
  110. );
  111. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  112. await provider.send(createFeishuBot({ feishuAppId: `mentions-${selection}` }), {
  113. botId: "feishu-1",
  114. provider: "feishu",
  115. providerUserId: "oc_group",
  116. text: selection ? "请选择" : "回答内容\n".repeat(6000),
  117. replyToMessageId: "om_question",
  118. mentionedUserIds: ["ou_alice", "ou_bob", "ou_alice"],
  119. ...(selection
  120. ? { selection: { action: "model.set" as const, title: "请选择", options: [] } }
  121. : {}),
  122. });
  123. expect(requests.length).toBeGreaterThan(selection ? 0 : 1);
  124. for (const [index, request] of requests.entries()) {
  125. expect(request.url).toContain("/om_question/reply");
  126. const card = JSON.parse(String(request.body.content));
  127. const mentions = JSON.stringify(card).match(/<at id=/g) ?? [];
  128. expect(mentions).toHaveLength(index === 0 ? 2 : 0);
  129. if (index === 0)
  130. expect(card.body.elements[0].content).toBe("<at id=ou_alice></at> <at id=ou_bob></at>");
  131. }
  132. },
  133. );
  134. it.each([false, true])(
  135. "bounds recalled-message fallback and keeps mentions for direct cards (topic=%s)",
  136. async (topic) => {
  137. const requests: Array<{ url: string; body: Record<string, unknown> }> = [];
  138. vi.stubGlobal(
  139. "fetch",
  140. vi.fn(async (url: string, init?: RequestInit) => {
  141. if (url.includes("tenant_access_token"))
  142. return Response.json({ code: 0, tenant_access_token: "fallback-token", expire: 3600 });
  143. requests.push({ url, body: JSON.parse(String(init?.body)) });
  144. return Response.json(
  145. url.endsWith("/reply")
  146. ? { code: 230011, msg: "recalled" }
  147. : { code: 0, data: { message_id: "om_result" } },
  148. );
  149. }),
  150. );
  151. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  152. const message: BotOutboundMessage = {
  153. botId: "feishu-1",
  154. provider: "feishu",
  155. providerUserId: "oc_group",
  156. text: "answer",
  157. replyToMessageId: "om_question",
  158. mentionedUserIds: ["ou_alice"],
  159. ...(topic ? { threadId: "omt_topic", rootMessageId: "om_root" } : {}),
  160. };
  161. const operation = provider.createTransientInteractionCard!(
  162. createFeishuBot({ feishuAppId: `recalled-mention-${topic}` }),
  163. message,
  164. );
  165. if (topic) await expect(operation).rejects.toMatchObject({ deliveryReplyUnavailable: true });
  166. else await expect(operation).resolves.toMatchObject({ providerMessageId: "om_result" });
  167. expect(requests).toHaveLength(2);
  168. expect(requests[0]?.url).toContain("/om_question/reply");
  169. expect(requests[1]?.url).toContain(topic ? "/om_root/reply" : "receive_id_type=chat_id");
  170. for (const request of requests)
  171. expect(JSON.parse(String(request.body.content)).body.elements[0].content).toBe(
  172. "<at id=ou_alice></at>",
  173. );
  174. },
  175. );
  176. it("never renders group mentions in private cards or accepts all/markup as a user ID", async () => {
  177. const cards: string[] = [];
  178. vi.stubGlobal(
  179. "fetch",
  180. vi.fn(async (url: string, init?: RequestInit) => {
  181. if (url.includes("tenant_access_token"))
  182. return Response.json({ code: 0, tenant_access_token: "private-token", expire: 3600 });
  183. cards.push(JSON.parse(String(init?.body)).content);
  184. return Response.json({ code: 0, data: { message_id: "om_result" } });
  185. }),
  186. );
  187. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  188. for (const providerUserId of ["ou_private", "oc_group"]) {
  189. await provider.send(createFeishuBot({ feishuAppId: "private-mentions" }), {
  190. botId: "feishu-1",
  191. provider: "feishu",
  192. providerUserId,
  193. text: "answer",
  194. mentionedUserIds:
  195. providerUserId === "ou_private" ? ["ou_alice"] : ["all", "ou_bad><at id=all"],
  196. });
  197. }
  198. expect(cards).toHaveLength(2);
  199. expect(cards.join("")).not.toContain("<at");
  200. });
  201. it.each(["feishu", "lark"] as const)(
  202. "refreshes %s tokens using their remaining lifetime",
  203. async (providerName) => {
  204. vi.useFakeTimers({ toFake: ["Date"] });
  205. vi.setSystemTime(new Date("2026-09-08T04:00:00Z"));
  206. let issued = 0;
  207. const authorizations: string[] = [];
  208. vi.stubGlobal(
  209. "fetch",
  210. vi.fn(async (url: string, init?: RequestInit) => {
  211. if (url.includes("tenant_access_token")) {
  212. issued += 1;
  213. return Response.json({ code: 0, tenant_access_token: `token-${issued}`, expire: 120 });
  214. }
  215. authorizations.push(new Headers(init?.headers).get("authorization") ?? "");
  216. return Response.json({ code: 0, data: { name: "Test group", chat_mode: "group" } });
  217. }),
  218. );
  219. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  220. const bot = createFeishuBot({
  221. provider: providerName,
  222. feishuAppId: `expiry-${providerName}`,
  223. });
  224. await provider.getGroupInfo!(bot, "oc_test");
  225. vi.setSystemTime(new Date("2026-09-08T04:00:30Z"));
  226. await provider.getGroupInfo!(bot, "oc_test");
  227. vi.setSystemTime(new Date("2026-09-08T04:01:01Z"));
  228. await provider.getGroupInfo!(bot, "oc_test");
  229. expect(issued).toBe(2);
  230. expect(authorizations).toEqual(["Bearer token-1", "Bearer token-1", "Bearer token-2"]);
  231. },
  232. );
  233. it("preserves a mention-only group message for contextual handling", () => {
  234. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  235. const result = provider.parseCallback({
  236. botId: "feishu-1",
  237. zcodeBotOpenId: "ou_bot",
  238. event: {
  239. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  240. message: {
  241. message_id: "om_empty",
  242. chat_id: "oc_a",
  243. chat_type: "group",
  244. message_type: "text",
  245. content: JSON.stringify({ text: "@_user_1" }),
  246. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" } }],
  247. },
  248. },
  249. });
  250. expect(result).toHaveLength(1);
  251. expect(result[0]?.text).toBe("@ou_bot");
  252. expect(result[0]?.commandText).toBe("");
  253. });
  254. it.each(
  255. ["bot", "app"].flatMap((senderType) => ["text", "file"].map((kind) => ({ senderType, kind }))),
  256. )(
  257. "preserves main-chat bot parent references ($senderType/$kind) and excludes self",
  258. async ({ senderType, kind }) => {
  259. const fetchMock = vi.fn(async (url: string) =>
  260. Response.json(
  261. url.includes("tenant_access_token")
  262. ? { code: 0, tenant_access_token: "token", expire: 7200 }
  263. : url.includes("bot/v3/info")
  264. ? { code: 0, bot: { open_id: "ou_bot" } }
  265. : {
  266. code: 0,
  267. data: {
  268. items: [
  269. {
  270. message_id: "om_parent",
  271. chat_id: "oc_a",
  272. msg_type: kind,
  273. body: {
  274. content: JSON.stringify(
  275. kind === "text"
  276. ? { text: "quoted context" }
  277. : { file_key: "file_parent", file_name: "context.txt" },
  278. ),
  279. },
  280. },
  281. ],
  282. },
  283. },
  284. ),
  285. );
  286. vi.stubGlobal("fetch", fetchMock);
  287. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  288. const bot = createFeishuBot({ feishuAppId: `main-reference-${senderType}-${kind}` });
  289. const event = {
  290. sender: { sender_type: senderType, sender_id: { open_id: "ou_other_bot" } },
  291. message: {
  292. message_id: "om_input",
  293. parent_id: "om_parent",
  294. chat_id: "oc_a",
  295. chat_type: "group",
  296. message_type: "text",
  297. content: JSON.stringify({ text: "@_bot review" }),
  298. mentions: [{ key: "@_bot", id: { open_id: "ou_bot" } }],
  299. },
  300. };
  301. const prepared = await provider.prepareCallbackPayload!(bot, { botId: bot.id, event });
  302. const input = provider.parseCallback(prepared)[0];
  303. if (kind === "text")
  304. expect(input?.referencedMessage).toMatchObject({
  305. messageId: "om_parent",
  306. text: "quoted context",
  307. });
  308. else
  309. expect(input?.attachments).toEqual([
  310. expect.objectContaining({
  311. providerFileId: "file_parent",
  312. providerMetadata: { resourceMessageId: "om_parent" },
  313. }),
  314. ]);
  315. fetchMock.mockClear();
  316. event.sender.sender_id.open_id = "ou_bot";
  317. const self = await provider.prepareCallbackPayload!(bot, { botId: bot.id, event });
  318. expect(provider.parseCallback(self)).toEqual([]);
  319. expect(fetchMock.mock.calls.some(([url]) => url.includes("/messages/om_parent"))).toBe(false);
  320. },
  321. );
  322. it.each(["text", "post", "interactive"])(
  323. "preserves quoted %s as data rather than a control command",
  324. async (kind) => {
  325. vi.stubGlobal(
  326. "fetch",
  327. vi.fn(async (url: string) =>
  328. Response.json(
  329. url.includes("tenant_access_token")
  330. ? { code: 0, tenant_access_token: "quoted-token", expire: 3600 }
  331. : url.includes("bot/v3/info")
  332. ? { code: 0, bot: { open_id: "ou_bot" } }
  333. : {
  334. code: 0,
  335. data: {
  336. items: [
  337. {
  338. message_id: "om_quote",
  339. chat_id: "oc_a",
  340. msg_type: kind,
  341. ...(kind === "interactive"
  342. ? {
  343. sender: { id: "quoted-interactive", sender_type: "app" },
  344. create_time: "1788921173004",
  345. }
  346. : {}),
  347. body: {
  348. content: JSON.stringify(
  349. kind === "text"
  350. ? { text: "/stop" }
  351. : kind === "post"
  352. ? {
  353. zh_cn: {
  354. content: [
  355. [
  356. { tag: "text", text: "/stop" },
  357. { tag: "img", image_key: "img_reference" },
  358. ],
  359. ],
  360. },
  361. }
  362. : !url.includes("card_msg_content_type=user_card_content")
  363. ? {
  364. elements: [
  365. [
  366. {
  367. tag: "text",
  368. text: "请升级至最新版本客户端,以查看内容",
  369. },
  370. ],
  371. ],
  372. }
  373. : {
  374. schema: "2.0",
  375. body: {
  376. elements: [
  377. { tag: "markdown", content: "/stop" },
  378. {
  379. tag: "button",
  380. value: { secretControl: "DO_NOT_INCLUDE" },
  381. },
  382. ],
  383. },
  384. },
  385. ),
  386. },
  387. },
  388. ],
  389. },
  390. },
  391. ),
  392. ),
  393. );
  394. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  395. const payload = await provider.prepareCallbackPayload!(
  396. createFeishuBot({ feishuAppId: `quoted-${kind}` }),
  397. {
  398. botId: "feishu-1",
  399. event: {
  400. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  401. message: {
  402. message_id: "om_input",
  403. parent_id: "om_quote",
  404. chat_id: "oc_a",
  405. chat_type: "group",
  406. message_type: "text",
  407. content: JSON.stringify({ text: "@_user_1" }),
  408. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" } }],
  409. },
  410. },
  411. },
  412. );
  413. expect(provider.parseCallback(payload)[0]).toMatchObject({
  414. text: "@ou_bot",
  415. commandText: "",
  416. referencedMessage: { messageId: "om_quote", text: "/stop" },
  417. });
  418. if (kind === "interactive")
  419. expect(provider.parseCallback(payload)[0]?.referencedMessage).toMatchObject({
  420. senderName: "Feishu",
  421. senderId: "quoted-interactive",
  422. sentAt: "2026-09-09T02:32:53.004Z",
  423. });
  424. if (kind === "post")
  425. expect(provider.parseCallback(payload)[0]?.attachments).toEqual([
  426. expect.objectContaining({
  427. providerFileId: "img_reference",
  428. providerMetadata: { resourceMessageId: "om_quote" },
  429. }),
  430. ]);
  431. },
  432. );
  433. it("bounds native card scope verification before the provider callback deadline", async () => {
  434. vi.stubGlobal(
  435. "fetch",
  436. vi.fn(async (url: string, init?: RequestInit) => {
  437. if (url.includes("tenant_access_token"))
  438. return Response.json({ code: 0, tenant_access_token: "card-deadline", expire: 3600 });
  439. return new Promise<Response>((_resolve, reject) => {
  440. init?.signal?.addEventListener("abort", () => reject(new Error("Card scope timeout")), {
  441. once: true,
  442. });
  443. });
  444. }),
  445. );
  446. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  447. await expect(
  448. adapter.prepareCallbackPayload!(createFeishuBot({ feishuAppId: "card-deadline" }), {
  449. event: {
  450. context: { open_chat_id: "oc_chat", open_message_id: "om_card" },
  451. action: {
  452. value: {
  453. groupCard: {
  454. chatId: "oc_chat",
  455. threadId: "omt_topic",
  456. taskId: "task",
  457. authorizationId: "auth",
  458. },
  459. },
  460. },
  461. },
  462. }),
  463. ).rejects.toThrow(/timeout/);
  464. }, 2500);
  465. it("rejects a card whose native topic differs from its embedded authority", async () => {
  466. vi.stubGlobal(
  467. "fetch",
  468. vi.fn(async (url: string) =>
  469. url.includes("tenant_access_token")
  470. ? Response.json({ code: 0, tenant_access_token: "card-topic", expire: 3600 })
  471. : Response.json({
  472. code: 0,
  473. data: {
  474. items: [{ message_id: "om_card", chat_id: "oc_chat", thread_id: "omt_actual" }],
  475. },
  476. }),
  477. ),
  478. );
  479. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  480. await expect(
  481. adapter.prepareCallbackPayload!(createFeishuBot({ feishuAppId: "card-topic" }), {
  482. event: {
  483. context: { open_chat_id: "oc_chat", open_message_id: "om_card" },
  484. action: {
  485. value: {
  486. groupCard: {
  487. chatId: "oc_chat",
  488. threadId: "omt_forged",
  489. taskId: "task",
  490. authorizationId: "auth",
  491. },
  492. },
  493. },
  494. },
  495. }),
  496. ).rejects.toThrow(/scope/);
  497. });
  498. it("resolves a dedicated-topic root from native message metadata and rejects cross-chat data", async () => {
  499. let chatId = "oc_topic";
  500. vi.stubGlobal(
  501. "fetch",
  502. vi.fn(async (url: string) =>
  503. url.includes("tenant_access_token")
  504. ? Response.json({ code: 0, tenant_access_token: "resolve-topic", expire: 3600 })
  505. : Response.json({
  506. code: 0,
  507. data: {
  508. items: [
  509. {
  510. message_id: "om_root",
  511. chat_id: chatId,
  512. thread_id: "omt_topic",
  513. thread_message_position: "0",
  514. msg_type: "text",
  515. body: { content: JSON.stringify({ text: "Topic title" }) },
  516. },
  517. ],
  518. },
  519. }),
  520. ),
  521. );
  522. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  523. const actor = {
  524. botId: "feishu-1",
  525. provider: "feishu" as const,
  526. chatType: "group" as const,
  527. chatId: "oc_topic",
  528. providerUserId: "owner",
  529. providerMessageId: "om_root",
  530. };
  531. expect(
  532. await adapter.resolveTopic!(createFeishuBot({ feishuAppId: "resolve-topic" }), actor),
  533. ).toEqual({
  534. threadId: "omt_topic",
  535. rootMessageId: "om_root",
  536. topicTitle: "Topic title",
  537. topicUrl:
  538. "https://applink.feishu.cn/client/thread/open?openthreadid=omt_topic&openchatid=oc_topic&open_thread_id=omt_topic&open_chat_id=oc_topic&thread_position=0",
  539. });
  540. chatId = "oc_secret";
  541. await expect(
  542. adapter.resolveTopic!(createFeishuBot({ feishuAppId: "resolve-topic" }), actor),
  543. ).rejects.toThrow(/scope/);
  544. });
  545. it("allows dedicated topic groups and reports their native chat mode", async () => {
  546. vi.stubGlobal(
  547. "fetch",
  548. vi.fn(async (url: string) =>
  549. url.includes("tenant_access_token")
  550. ? Response.json({ code: 0, tenant_access_token: "topic-group-token", expire: 3600 })
  551. : Response.json({ code: 0, data: { name: "Topic group", chat_mode: "topic" } }),
  552. ),
  553. );
  554. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  555. expect(
  556. await adapter.getGroupInfo!(createFeishuBot({ feishuAppId: "topic-group" }), "oc_topic"),
  557. ).toMatchObject({ name: "Topic group", chatMode: "topic" });
  558. });
  559. it.each(["file", "image", "post"])(
  560. "resolves archived %s resources from their native message",
  561. async (kind) => {
  562. vi.stubGlobal(
  563. "fetch",
  564. vi.fn(async (url: string) =>
  565. url.includes("tenant_access_token")
  566. ? Response.json({ code: 0, tenant_access_token: "resource-token", expire: 3600 })
  567. : Response.json({
  568. code: 0,
  569. data: {
  570. items: [
  571. {
  572. message_id: "om_file",
  573. chat_id: "oc_chat",
  574. thread_id: "omt_topic",
  575. msg_type: kind,
  576. body: {
  577. content: JSON.stringify(
  578. kind === "file"
  579. ? { file_key: "file_key", file_name: "sample.txt" }
  580. : kind === "image"
  581. ? { image_key: "img_key" }
  582. : { zh_cn: { content: [[{ tag: "img", image_key: "img_key" }]] } },
  583. ),
  584. },
  585. },
  586. ],
  587. },
  588. }),
  589. ),
  590. );
  591. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  592. const result = await adapter.readTopicResourceMessage!(
  593. createFeishuBot({ feishuAppId: `resource-${kind}` }),
  594. {
  595. messageId: "om_file",
  596. chatId: "oc_chat",
  597. threadId: "omt_topic",
  598. },
  599. );
  600. expect(result.attachments).toHaveLength(1);
  601. expect(result.attachments[0]).toMatchObject({
  602. providerFileId: kind === "file" ? "file_key" : "img_key",
  603. providerMetadata: { resourceMessageId: "om_file" },
  604. });
  605. },
  606. );
  607. it("rejects a missing archived native resource instead of returning an empty file", async () => {
  608. vi.stubGlobal(
  609. "fetch",
  610. vi.fn(async (url: string) =>
  611. url.includes("tenant_access_token")
  612. ? Response.json({ code: 0, tenant_access_token: "resource-empty-token", expire: 3600 })
  613. : Response.json({ code: 0, data: { items: [] } }),
  614. ),
  615. );
  616. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  617. await expect(
  618. adapter.readTopicResourceMessage!(createFeishuBot({ feishuAppId: "resource-empty" }), {
  619. messageId: "om_file",
  620. chatId: "oc_chat",
  621. threadId: "omt_topic",
  622. }),
  623. ).rejects.toThrow();
  624. });
  625. it("preserves missing permissions even on the first root invocation", async () => {
  626. vi.stubGlobal(
  627. "fetch",
  628. vi.fn(async (url: string) =>
  629. url.includes("tenant_access_token")
  630. ? Response.json({ code: 0, tenant_access_token: "permission-token", expire: 3600 })
  631. : Response.json({ code: 99991672, msg: "Access denied: im:message.group_msg" }),
  632. ),
  633. );
  634. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  635. await expect(
  636. adapter.readTopicHistory!(createFeishuBot({ feishuAppId: "history-permission" }), {
  637. chatId: "chat",
  638. threadId: "thread",
  639. rootMessageId: "root",
  640. messageId: "root",
  641. }),
  642. ).rejects.toBeInstanceOf(TopicHistoryPermissionError);
  643. });
  644. it.each(["before-checkpoint", "after-invocation", "deleted", "required"])(
  645. "only expands history cards inside the required window (%s)",
  646. async (position) => {
  647. const native = (id: string) => ({
  648. message_id: id,
  649. chat_id: "oc_chat",
  650. thread_id: "omt_topic",
  651. sender: { id: "ou_bot", sender_type: "app" },
  652. create_time: "1",
  653. msg_type: id === "om_card" ? "interactive" : "text",
  654. body: { content: JSON.stringify({ text: id }) },
  655. ...(position === "deleted" && id === "om_card" ? { deleted: true } : {}),
  656. });
  657. const order =
  658. position === "after-invocation"
  659. ? ["om_card", "om_current", "om_checkpoint"]
  660. : position === "before-checkpoint"
  661. ? ["om_current", "om_checkpoint", "om_card"]
  662. : ["om_current", "om_card", "om_checkpoint"];
  663. const fetchMock = vi.fn(async (url: string) => {
  664. if (url.includes("tenant_access_token"))
  665. return Response.json({ code: 0, tenant_access_token: "token", expire: 3600 });
  666. if (url.includes("/messages/om_card"))
  667. return Response.json({ code: 999, msg: "unreadable" }, { status: 404 });
  668. if (url.includes("/members"))
  669. return Response.json({ code: 0, data: { items: [], has_more: false } });
  670. return Response.json({ code: 0, data: { items: order.map(native), has_more: false } });
  671. });
  672. vi.stubGlobal("fetch", fetchMock);
  673. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  674. const pending = adapter.readTopicHistory!(
  675. createFeishuBot({ feishuAppId: `window-${position}` }),
  676. {
  677. chatId: "oc_chat",
  678. threadId: "omt_topic",
  679. rootMessageId: "om_root",
  680. messageId: "om_current",
  681. checkpoint: "om_checkpoint",
  682. },
  683. );
  684. if (position === "required") await expect(pending).rejects.toThrow();
  685. else {
  686. expect((await pending).messages).toEqual([]);
  687. expect(fetchMock.mock.calls.some(([url]) => url.includes("/messages/om_card"))).toBe(false);
  688. }
  689. },
  690. );
  691. it("reads native thread pages without fetching full chat history", async () => {
  692. const native = (id: string) => ({
  693. message_id: id,
  694. chat_id: "oc_chat",
  695. thread_id: "omt_topic",
  696. sender: { id: "ou_user", sender_type: "user" },
  697. create_time: "1",
  698. parent_id: id === "om_old" ? "om_root" : undefined,
  699. msg_type: id === "om_old" ? "post" : "text",
  700. body: {
  701. content: JSON.stringify(
  702. id === "om_old"
  703. ? {
  704. zh_cn: {
  705. title: "Original title",
  706. content: [
  707. [
  708. { tag: "text", text: "original lines" },
  709. { tag: "img", image_key: "img_history" },
  710. ],
  711. ],
  712. },
  713. }
  714. : { text: id },
  715. ),
  716. },
  717. });
  718. const fetchMock = vi.fn(async (url: string) => {
  719. if (url.includes("tenant_access_token"))
  720. return Response.json({ code: 0, tenant_access_token: "history-token", expire: 3600 });
  721. if (url.includes("/members"))
  722. return Response.json({
  723. code: 0,
  724. data: { items: [{ member_id: "ou_user", name: "Alice" }], has_more: false },
  725. });
  726. if (url.includes("/messages/om_root"))
  727. return Response.json({ code: 0, data: { items: [native("om_root")] } });
  728. return Response.json({
  729. code: 0,
  730. data: { items: [native("om_current"), native("om_old")], has_more: false },
  731. });
  732. });
  733. vi.stubGlobal("fetch", fetchMock);
  734. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  735. const result = await adapter.readTopicHistory!(
  736. createFeishuBot({ feishuAppId: "topic-history" }),
  737. {
  738. chatId: "oc_chat",
  739. threadId: "omt_topic",
  740. rootMessageId: "om_root",
  741. messageId: "om_current",
  742. },
  743. );
  744. expect(result.messages.map((m) => m.id)).toEqual(["om_root", "om_old"]);
  745. expect(result.messages[1]).toMatchObject({
  746. senderName: "Alice",
  747. senderId: "ou_user",
  748. parentId: "om_root",
  749. attachments: [{ kind: "image", name: expect.any(String) }],
  750. });
  751. expect(result.messages[1]!.text).toContain("original lines");
  752. const urls = fetchMock.mock.calls.map(([url]) => url);
  753. expect(urls.some((url) => url.includes("container_id_type=thread"))).toBe(true);
  754. expect(urls.some((url) => url.includes("container_id_type=chat"))).toBe(false);
  755. });
  756. it.each([false, true])(
  757. "keeps topic output inside its thread (selection=%s)",
  758. async (selection) => {
  759. const fetchMock = vi.fn(async (url: string, _init?: RequestInit) =>
  760. url.includes("tenant_access_token")
  761. ? Response.json({ code: 0, tenant_access_token: "topic-token", expire: 3600 })
  762. : Response.json({ code: 0, data: { message_id: "om_sent" } }),
  763. );
  764. vi.stubGlobal("fetch", fetchMock);
  765. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  766. await adapter.send(createFeishuBot({ feishuAppId: `topic-send-${selection}` }), {
  767. botId: "feishu-1",
  768. provider: "feishu",
  769. providerUserId: "oc_chat",
  770. text: "Result",
  771. threadId: "omt_topic",
  772. rootMessageId: "om_root",
  773. ...(selection
  774. ? {
  775. selection: {
  776. id: "queue",
  777. title: "Waiting",
  778. action: "queue.cancel" as const,
  779. options: [{ id: "/queue-cancel input", label: "Cancel" }],
  780. },
  781. }
  782. : {}),
  783. });
  784. const sent = fetchMock.mock.calls.find(([url]) => url.endsWith("/om_root/reply"));
  785. expect(sent).toBeDefined();
  786. expect(JSON.parse(String(sent?.[1]?.body))).toMatchObject({ reply_in_thread: true });
  787. expect(fetchMock.mock.calls.some(([url]) => url.includes("messages?"))).toBe(false);
  788. },
  789. );
  790. it("rejects topic output without an original topic message instead of posting to chat", async () => {
  791. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  792. await expect(
  793. adapter.send(createFeishuBot(), {
  794. botId: "feishu-1",
  795. provider: "feishu",
  796. providerUserId: "oc_chat",
  797. text: "Result",
  798. threadId: "omt_topic",
  799. }),
  800. ).rejects.toThrow(/topic/i);
  801. });
  802. it.each(["om_request", undefined])(
  803. "keeps transient topic cards in the source thread (%s)",
  804. async (replyToMessageId) => {
  805. const fetchMock = vi.fn(async (url: string, _init?: RequestInit) =>
  806. url.includes("tenant_access_token")
  807. ? Response.json({ code: 0, tenant_access_token: "transient-token", expire: 3600 })
  808. : Response.json({ code: 0, data: { message_id: "om_card" } }),
  809. );
  810. vi.stubGlobal("fetch", fetchMock);
  811. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  812. await adapter.createTransientInteractionCard!(
  813. createFeishuBot({ feishuAppId: `transient-topic-${replyToMessageId}` }),
  814. {
  815. botId: "feishu-1",
  816. provider: "feishu",
  817. providerUserId: "oc_chat",
  818. text: "Approval required",
  819. threadId: "omt_topic",
  820. rootMessageId: "om_root",
  821. replyToMessageId,
  822. },
  823. );
  824. const sent = fetchMock.mock.calls.find(([url]) =>
  825. url.endsWith(`/${replyToMessageId ?? "om_root"}/reply`),
  826. );
  827. expect(sent).toBeDefined();
  828. expect(JSON.parse(String(sent?.[1]?.body))).toMatchObject({ reply_in_thread: true });
  829. expect(fetchMock.mock.calls.some(([url]) => url.includes("messages?"))).toBe(false);
  830. },
  831. );
  832. it("rejects transient topic cards without an anchor before provider I/O", async () => {
  833. const fetchMock = vi.fn();
  834. vi.stubGlobal("fetch", fetchMock);
  835. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  836. await expect(
  837. adapter.createTransientInteractionCard!(createFeishuBot(), {
  838. botId: "feishu-1",
  839. provider: "feishu",
  840. providerUserId: "oc_chat",
  841. text: "Approval required",
  842. threadId: "omt_topic",
  843. }),
  844. ).rejects.toThrow(/topic/i);
  845. expect(fetchMock).not.toHaveBeenCalled();
  846. });
  847. it("renders queue cancellation in one compact row with its original command", async () => {
  848. const fetchMock = vi.fn(async (url: string) =>
  849. String(url).includes("tenant_access_token")
  850. ? Response.json({ code: 0, tenant_access_token: "queue-token", expire: 3600 })
  851. : Response.json({ code: 0, data: { message_id: "om_card" } }),
  852. );
  853. vi.stubGlobal("fetch", fetchMock);
  854. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  855. const handle = await adapter.send(
  856. createFeishuBot({ id: "compact-queue", feishuAppId: "cli_compact_queue" }),
  857. {
  858. botId: "compact-queue",
  859. provider: "feishu",
  860. providerUserId: "ou_owner",
  861. text: "等待执行",
  862. selection: {
  863. id: "queue-one",
  864. title: "已排队",
  865. action: "queue.cancel",
  866. showCancel: false,
  867. options: [{ id: "/queue-cancel one", label: "取消" }],
  868. },
  869. },
  870. );
  871. expect(handle).toEqual({ providerMessageId: "om_card" });
  872. const sent = fetchMock.mock.calls.find(([url]) => String(url).includes("/messages?"));
  873. const body = JSON.parse(String((sent as unknown as [string, RequestInit])[1].body));
  874. const card = JSON.parse(body.content);
  875. expect(card.body.elements).toHaveLength(1);
  876. expect(card.body.elements[0].tag).toBe("column_set");
  877. expect(card.body.elements[0].columns[0].elements[0].content).toBe("等待执行");
  878. expect(card.body.elements[0].columns[1].elements[0].behaviors[0].value.command).toBe(
  879. "/queue-cancel one",
  880. );
  881. });
  882. it.each(["feishu", "lark"] as const)(
  883. "replaces only its own lifecycle reaction (%s)",
  884. async (provider) => {
  885. const bot = createFeishuBot({
  886. provider,
  887. id: `reaction-${provider}`,
  888. feishuAppId: `app-${provider}`,
  889. });
  890. const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
  891. if (String(url).includes("tenant_access_token"))
  892. return Response.json({ code: 0, tenant_access_token: "reaction-token", expire: 3600 });
  893. if (init?.method === "GET")
  894. return Response.json({
  895. code: 0,
  896. data: {
  897. items: [
  898. {
  899. reaction_id: "ours",
  900. operator: { operator_type: "app", operator_id: bot.feishuAppId },
  901. reaction_type: { emoji_type: "OneSecond" },
  902. },
  903. {
  904. reaction_id: "member",
  905. operator: { operator_type: "user", operator_id: "ou_member" },
  906. reaction_type: { emoji_type: "OneSecond" },
  907. },
  908. {
  909. reaction_id: "other-app",
  910. operator: { operator_type: "app", operator_id: "other" },
  911. reaction_type: { emoji_type: "OnIt" },
  912. },
  913. ],
  914. },
  915. });
  916. return Response.json({ code: 0, data: { reaction_id: "new" } });
  917. });
  918. vi.stubGlobal("fetch", fetchMock);
  919. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  920. await adapter.updateInputReaction!(bot, "om_input", "working");
  921. const deletes = fetchMock.mock.calls.filter(([, init]) => init?.method === "DELETE");
  922. expect(deletes).toHaveLength(1);
  923. expect(deletes[0]?.[0]).toContain("/reactions/ours");
  924. const adds = fetchMock.mock.calls.filter(
  925. ([url, init]) => init?.method === "POST" && url.endsWith("/reactions"),
  926. );
  927. expect(JSON.parse(String(adds[0]?.[1]?.body))).toEqual({
  928. reaction_type: { emoji_type: "OnIt" },
  929. });
  930. expect(adds[0]?.[0]).toContain(provider === "lark" ? "open.larksuite.com" : "open.feishu.cn");
  931. },
  932. );
  933. it("splits streaming cards before Card JSON 2.0 reaches the 200-element limit", () => {
  934. const segments = splitFeishuStreamingCardStates({
  935. providerUserId: "ou_user",
  936. locale: "zh-CN",
  937. blocks: Array.from({ length: 181 }, (_, index) => ({
  938. type: "message" as const,
  939. text: `message-${index}`,
  940. })),
  941. status: "running",
  942. });
  943. expect(segments).toHaveLength(2);
  944. expect(segments[0]?.status).toBe("sealed");
  945. expect(segments[1]?.status).toBe("running");
  946. expect(segments.flatMap((segment) => segment.blocks)).toHaveLength(181);
  947. for (const segment of segments) {
  948. expect(countFeishuCardTaggedElements(segment)).toBeLessThanOrEqual(180);
  949. }
  950. });
  951. it("returns the complete business card only after card action processing succeeds", async () => {
  952. let completeCallback: ((message: BotOutboundMessage) => void) | undefined;
  953. const callbackGate = new Promise<BotOutboundMessage>((resolve) => {
  954. completeCallback = resolve;
  955. });
  956. const handlers = createFeishuWebSocketEventHandlers({
  957. bot: createFeishuBot(),
  958. onPayload: vi.fn(async () => callbackGate),
  959. });
  960. let settled = false;
  961. const response = handlers["card.action.trigger"]({
  962. action: {
  963. value: {
  964. command: "/approve request-1 option-1",
  965. zcodeCardText: "Review this implementation plan.",
  966. },
  967. },
  968. }).finally(() => {
  969. settled = true;
  970. });
  971. await Promise.resolve();
  972. expect(settled).toBe(false);
  973. completeCallback?.({
  974. botId: "feishu-1",
  975. provider: "feishu",
  976. providerUserId: "ou_user",
  977. text: "2/2\n第二题",
  978. selection: {
  979. id: "elicitation-request-1-1",
  980. token: "abc123def456",
  981. title: "2/2\n第二题",
  982. action: "elicitation.respond",
  983. options: [{ id: "next", label: "下一项" }],
  984. },
  985. elicitation: {
  986. requestId: "request-1",
  987. taskId: "task-1",
  988. currentQuestionIndex: 1,
  989. questions: [
  990. { question: "第一题", options: [{ value: "first", label: "第一项" }] },
  991. { question: "第二题", options: [{ value: "next", label: "下一项" }] },
  992. ],
  993. answers: { "0": ["first"] },
  994. status: "pending",
  995. },
  996. });
  997. const result = await response;
  998. expect(result).toMatchObject({ card: { type: "raw" } });
  999. expect(JSON.stringify(result)).toContain("第一题");
  1000. expect(JSON.stringify(result)).toContain("第二题");
  1001. expect(JSON.stringify(result)).toContain("abc123def456");
  1002. });
  1003. it("does not return a success card when card action processing rejects", async () => {
  1004. const handlers = createFeishuWebSocketEventHandlers({
  1005. bot: createFeishuBot(),
  1006. onPayload: vi.fn(async () => {
  1007. throw new Error("callback failed");
  1008. }),
  1009. });
  1010. await expect(
  1011. handlers["card.action.trigger"]({
  1012. action: {
  1013. value: {
  1014. command: "/approve request-1 option-1",
  1015. zcodeCardText: "Review this implementation plan.",
  1016. },
  1017. },
  1018. }),
  1019. ).rejects.toThrow("callback failed");
  1020. });
  1021. it("acknowledges slow card actions within the platform deadline and marks deferred delivery", async () => {
  1022. vi.useFakeTimers();
  1023. let payload: Record<string, unknown> | undefined;
  1024. let finish!: (value: undefined) => void;
  1025. const handlers = createFeishuWebSocketEventHandlers({
  1026. bot: createFeishuBot(),
  1027. onPayload: async (value) => {
  1028. payload = value as Record<string, unknown>;
  1029. return await new Promise<undefined>((resolve) => {
  1030. finish = resolve;
  1031. });
  1032. },
  1033. });
  1034. const response = handlers["card.action.trigger"]({
  1035. event: { context: { open_chat_id: "oc_group" } },
  1036. });
  1037. await vi.advanceTimersByTimeAsync(2000);
  1038. expect(await response).toEqual({});
  1039. expect(payload?.zcodeFeishuCardResponseState).toEqual({ deferred: true });
  1040. finish(undefined);
  1041. });
  1042. it("keeps WebSocket bot identity trusted when event payload contains routing fields", async () => {
  1043. const onPayload = vi.fn(async () => undefined);
  1044. const handlers = createFeishuWebSocketEventHandlers({ bot: createFeishuBot(), onPayload });
  1045. await handlers["im.message.receive_v1"]({ botId: "other", zcodeProvider: "lark" });
  1046. expect(onPayload).toHaveBeenLastCalledWith(
  1047. expect.objectContaining({ botId: "feishu-1", zcodeProvider: "feishu" }),
  1048. );
  1049. await handlers["card.action.trigger"]({
  1050. botId: "other",
  1051. zcodeFeishuSynchronousCardAction: false,
  1052. });
  1053. expect(onPayload).toHaveBeenLastCalledWith(
  1054. expect.objectContaining({ botId: "feishu-1", zcodeFeishuSynchronousCardAction: true }),
  1055. );
  1056. });
  1057. it("requires sender open_id for group authority", () => {
  1058. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1059. expect(
  1060. provider.parseCallback({
  1061. botId: "feishu-1",
  1062. zcodeBotOpenId: "ou_bot",
  1063. event: {
  1064. sender: { sender_type: "user", sender_id: { user_id: "ou_user" } },
  1065. message: {
  1066. chat_id: "oc_chat",
  1067. message_id: "om_message",
  1068. chat_type: "group",
  1069. content: JSON.stringify({ text: "@_user_1 /status" }),
  1070. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" } }],
  1071. },
  1072. },
  1073. }),
  1074. ).toEqual([]);
  1075. });
  1076. it.each([true, false])(
  1077. "recognizes only this bot as the topic root author (own=%s)",
  1078. async (own) => {
  1079. vi.stubGlobal(
  1080. "fetch",
  1081. vi.fn(async (url: string) =>
  1082. Response.json(
  1083. url.includes("tenant_access_token")
  1084. ? { code: 0, tenant_access_token: "token", expire: 3600 }
  1085. : url.includes("bot/v3/info")
  1086. ? { code: 0, bot: { open_id: "ou_bot" } }
  1087. : {
  1088. code: 0,
  1089. data: {
  1090. items: [
  1091. {
  1092. message_id: "root",
  1093. chat_id: "chat",
  1094. thread_id: "topic",
  1095. msg_type: "text",
  1096. sender: {
  1097. id: own ? "app-root" : "other-app",
  1098. id_type: "app_id",
  1099. sender_type: "app",
  1100. },
  1101. body: { content: JSON.stringify({ text: "root reply" }) },
  1102. },
  1103. ],
  1104. },
  1105. },
  1106. ),
  1107. ),
  1108. );
  1109. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1110. const prepared = await provider.prepareCallbackPayload!(
  1111. createFeishuBot({ feishuAppId: "app-root" }),
  1112. {
  1113. botId: "feishu-1",
  1114. event: {
  1115. sender: { sender_type: "user", sender_id: { open_id: "user" } },
  1116. message: {
  1117. message_id: "incoming",
  1118. chat_type: "group",
  1119. chat_id: "chat",
  1120. thread_id: "topic",
  1121. root_id: "root",
  1122. parent_id: "root",
  1123. content: JSON.stringify({ text: "continue" }),
  1124. mentions: [],
  1125. },
  1126. },
  1127. },
  1128. );
  1129. expect(provider.parseCallback(prepared)[0]).toMatchObject({
  1130. mentionedBot: false,
  1131. topicRootIsCurrentBot: own,
  1132. referencedMessage: { text: "root reply" },
  1133. });
  1134. const again = await provider.prepareCallbackPayload!(
  1135. createFeishuBot({ feishuAppId: "app-root" }),
  1136. { ...(prepared as object), zcodeTopicActive: false, zcodeTopicHasAcceptedInput: true },
  1137. );
  1138. expect(provider.parseCallback(again)[0]?.referencedMessage).toBeUndefined();
  1139. expect(
  1140. vi.mocked(fetch).mock.calls.filter(([url]) => String(url).includes("im/v1/messages/")),
  1141. ).toHaveLength(1);
  1142. },
  1143. );
  1144. it("preserves human and other-app topic messages but ignores itself", () => {
  1145. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1146. const payload = {
  1147. botId: "feishu-1",
  1148. zcodeBotOpenId: "ou_bot",
  1149. event: {
  1150. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  1151. message: {
  1152. chat_type: "group",
  1153. chat_id: "oc_chat",
  1154. thread_id: "omt_topic",
  1155. root_id: "om_root",
  1156. message_id: "om_input",
  1157. content: JSON.stringify({ text: "@_user_1 hello" }),
  1158. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" } }],
  1159. },
  1160. },
  1161. };
  1162. expect(provider.parseCallback(payload)[0]?.actor).toMatchObject({
  1163. chatId: "oc_chat",
  1164. threadId: "omt_topic",
  1165. rootMessageId: "om_root",
  1166. });
  1167. payload.event.message.mentions = [];
  1168. payload.event.message.content = JSON.stringify({ text: "continue" });
  1169. expect(provider.parseCallback(payload)[0]).toMatchObject({
  1170. text: "continue",
  1171. mentionedBot: false,
  1172. actor: { threadId: "omt_topic" },
  1173. });
  1174. payload.event.sender.sender_type = "bot";
  1175. expect(provider.parseCallback(payload)[0]).toMatchObject({
  1176. senderType: "app",
  1177. text: "continue",
  1178. actor: { providerUserId: "ou_user" },
  1179. });
  1180. payload.event.sender.sender_id.open_id = "ou_bot";
  1181. expect(provider.parseCallback(payload)).toEqual([]);
  1182. payload.event.sender.sender_id.open_id = "ou_other_bot";
  1183. payload.event.message.thread_id = "";
  1184. expect(provider.parseCallback(payload)).toEqual([]);
  1185. payload.event.message.mentions = [{ key: "@_bot", id: { open_id: "ou_bot" }, name: "Bot" }];
  1186. payload.event.message.content = JSON.stringify({ text: "@_bot hello" });
  1187. expect(provider.parseCallback(payload)[0]).toMatchObject({
  1188. senderType: "app",
  1189. mentionedBot: true,
  1190. });
  1191. });
  1192. it.each(["feishu", "lark"])(
  1193. "%s ignores bot cards instead of admitting visible text",
  1194. (provider) => {
  1195. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  1196. const payload = {
  1197. botId: "feishu-1",
  1198. zcodeProvider: provider,
  1199. zcodeBotOpenId: "ou_bot",
  1200. event: {
  1201. sender: { sender_type: "bot", sender_id: { open_id: "ou_other_bot" } },
  1202. message: {
  1203. chat_type: "group",
  1204. chat_id: "oc_chat",
  1205. thread_id: "omt_topic",
  1206. root_id: "om_root",
  1207. message_id: "om_card",
  1208. message_type: "interactive",
  1209. content: JSON.stringify({
  1210. body: {
  1211. elements: [
  1212. { tag: "markdown", content: "Analysis completed" },
  1213. {
  1214. tag: "button",
  1215. text: { content: "Details" },
  1216. value: { text: "/approve secret" },
  1217. },
  1218. ],
  1219. },
  1220. }),
  1221. },
  1222. },
  1223. };
  1224. expect(adapter.parseCallback(payload)).toEqual([]);
  1225. payload.event.sender.sender_type = "app";
  1226. expect(adapter.parseCallback(payload)).toEqual([]);
  1227. payload.event.sender.sender_id.open_id = "";
  1228. expect(adapter.parseCallback(payload)).toEqual([]);
  1229. },
  1230. );
  1231. it("ignores bot confirmation replies to a bot card while retaining human quotes", async () => {
  1232. vi.stubGlobal(
  1233. "fetch",
  1234. vi.fn(async (url: string) =>
  1235. Response.json(
  1236. url.includes("tenant_access_token")
  1237. ? { code: 0, tenant_access_token: "card-token", expire: 3600 }
  1238. : url.includes("bot/v3/info")
  1239. ? { code: 0, bot: { open_id: "ou_bot" } }
  1240. : {
  1241. code: 0,
  1242. data: {
  1243. items: [
  1244. {
  1245. message_id: "om_card",
  1246. chat_id: "oc_a",
  1247. thread_id: "omt_a",
  1248. msg_type: "interactive",
  1249. sender: { id: "ou_other", sender_type: "app" },
  1250. body: {
  1251. content: JSON.stringify({
  1252. elements: [
  1253. { tag: "markdown", content: "Permission options" },
  1254. {
  1255. tag: "button",
  1256. text: { content: "Allow" },
  1257. value: { command: "/approve" },
  1258. },
  1259. ],
  1260. }),
  1261. },
  1262. },
  1263. ],
  1264. },
  1265. },
  1266. ),
  1267. ),
  1268. );
  1269. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  1270. const event = {
  1271. sender: { sender_type: "bot", sender_id: { open_id: "ou_other" } },
  1272. message: {
  1273. message_id: "om_confirm",
  1274. chat_id: "oc_a",
  1275. chat_type: "group",
  1276. thread_id: "omt_a",
  1277. parent_id: "om_card",
  1278. message_type: "text",
  1279. content: JSON.stringify({ text: "Permission response submitted." }),
  1280. mentions: [{ key: "@_bot", id: { open_id: "ou_bot" }, name: "Bot" }],
  1281. },
  1282. };
  1283. const bot = createFeishuBot({ feishuAppId: "card-confirm" });
  1284. expect(
  1285. adapter.parseCallback(await adapter.prepareCallbackPayload!(bot, { botId: bot.id, event })),
  1286. ).toEqual([]);
  1287. event.sender.sender_type = "user";
  1288. expect(
  1289. adapter.parseCallback(await adapter.prepareCallbackPayload!(bot, { botId: bot.id, event }))[0]
  1290. ?.referencedMessage?.text,
  1291. ).toBe("Permission options\nAllow");
  1292. });
  1293. it.each(["feishu", "lark"])(
  1294. "%s admits plain conversation cards with native mentions",
  1295. async (provider) => {
  1296. const adapter = createFeishuBotProvider({ loadCredential: async () => "secret" });
  1297. const payload = {
  1298. botId: "feishu-1",
  1299. zcodeProvider: provider,
  1300. zcodeBotOpenId: "ou_bot",
  1301. event: {
  1302. sender: { sender_type: "bot", sender_id: { open_id: "ou_other_bot" } },
  1303. message: {
  1304. message_id: "om_plain",
  1305. chat_id: "oc_a",
  1306. chat_type: "group",
  1307. thread_id: "omt_a",
  1308. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" }, name: "Bot" }],
  1309. message_type: "interactive",
  1310. content: JSON.stringify({
  1311. body: {
  1312. elements: [
  1313. { tag: "markdown", content: "<at id=ou_sender_scope></at> What date is today?" },
  1314. ],
  1315. },
  1316. }),
  1317. },
  1318. },
  1319. };
  1320. expect(adapter.parseCallback(payload)[0]).toMatchObject({
  1321. text: "@Bot What date is today?",
  1322. mentionedBot: true,
  1323. senderType: "app",
  1324. contentParts: [
  1325. { type: "channelMention", targetId: "ou_bot" },
  1326. { type: "text", text: " What date is today?" },
  1327. ],
  1328. });
  1329. const actualContent = payload.event.message.content;
  1330. vi.stubGlobal(
  1331. "fetch",
  1332. vi.fn(async (url: string) =>
  1333. Response.json(
  1334. url.includes("tenant_access_token")
  1335. ? { code: 0, tenant_access_token: "plain-token", expire: 3600 }
  1336. : url.includes("bot/v3/info")
  1337. ? { code: 0, bot: { open_id: "ou_bot" } }
  1338. : {
  1339. code: 0,
  1340. data: {
  1341. items: [
  1342. {
  1343. message_id: "om_plain",
  1344. chat_id: "oc_a",
  1345. thread_id: "omt_a",
  1346. body: { content: actualContent },
  1347. },
  1348. ],
  1349. },
  1350. },
  1351. ),
  1352. ),
  1353. );
  1354. payload.event.message.content = JSON.stringify({
  1355. elements: [[{ tag: "text", text: "请升级至最新版本客户端,以查看内容" }]],
  1356. });
  1357. const prepared = await adapter.prepareCallbackPayload!(
  1358. createFeishuBot({
  1359. provider: provider as "feishu" | "lark",
  1360. feishuAppId: `plain-${provider}`,
  1361. }),
  1362. payload,
  1363. );
  1364. expect(adapter.parseCallback(prepared)[0]?.text).toBe("@Bot What date is today?");
  1365. payload.event.message.content = actualContent;
  1366. payload.event.sender.sender_id.open_id = "ou_bot";
  1367. expect(adapter.parseCallback(payload)).toEqual([]);
  1368. },
  1369. );
  1370. it("parses Feishu text callbacks into inbound bot messages", () => {
  1371. const provider = createFeishuBotProvider({
  1372. loadCredential: vi.fn(async () => "secret"),
  1373. });
  1374. expect(
  1375. provider.parseCallback({
  1376. botId: "feishu-1",
  1377. token: "token",
  1378. zcodeBotOpenId: "ou_bot",
  1379. event: {
  1380. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  1381. message: {
  1382. chat_id: "oc_chat",
  1383. message_id: "om_message",
  1384. chat_type: "group",
  1385. content: JSON.stringify({ text: "@_user_1 /status" }),
  1386. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" }, name: "ZCode" }],
  1387. },
  1388. },
  1389. }),
  1390. ).toEqual([
  1391. {
  1392. botId: "feishu-1",
  1393. text: "@ZCode /status",
  1394. commandText: "/status",
  1395. contentParts: [
  1396. {
  1397. type: "channelMention",
  1398. channel: "feishu",
  1399. entityType: "unknown",
  1400. idType: "open_id",
  1401. name: "ZCode",
  1402. refId: "om_message:m1",
  1403. targetId: "ou_bot",
  1404. },
  1405. { type: "text", text: " /status" },
  1406. ],
  1407. botOpenId: "ou_bot",
  1408. mentionedBot: true,
  1409. topicRootIsCurrentBot: false,
  1410. actor: {
  1411. provider: "feishu",
  1412. botId: "feishu-1",
  1413. providerUserId: "ou_user",
  1414. chatType: "group",
  1415. chatId: "oc_chat",
  1416. providerMessageId: "om_message",
  1417. },
  1418. },
  1419. ]);
  1420. });
  1421. it.each(["feishu", "lark"])("preserves ordered native post mentions on %s", (providerName) => {
  1422. const provider = createFeishuBotProvider({ loadCredential: async () => "secret" });
  1423. const messages = provider.parseCallback({
  1424. botId: "native-post",
  1425. zcodeProvider: providerName,
  1426. zcodeBotOpenId: "ou_bot",
  1427. event: {
  1428. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  1429. message: {
  1430. chat_id: "oc_group",
  1431. message_id: "om_post",
  1432. chat_type: "group",
  1433. message_type: "post",
  1434. mentions: [
  1435. { key: "@_user_1", id: { open_id: "ou_bot" }, name: "ZBot" },
  1436. { key: "@_user_2", id: { open_id: "ou_target" }, name: "Ryan Bot" },
  1437. ],
  1438. content: JSON.stringify({
  1439. content: [
  1440. [
  1441. { tag: "at", user_id: "ou_bot", user_name: "ZBot" },
  1442. { tag: "text", text: "帮我 " },
  1443. { tag: "at", user_id: "ou_target", user_name: "Ryan Bot" },
  1444. { tag: "text", text: " 确认" },
  1445. ],
  1446. ],
  1447. }),
  1448. },
  1449. },
  1450. });
  1451. expect(messages[0]).toMatchObject({
  1452. text: "@ZBot帮我 @Ryan Bot 确认",
  1453. commandText: "帮我 @Ryan Bot 确认",
  1454. contentParts: [
  1455. { type: "channelMention", targetId: "ou_bot", name: "ZBot", channel: providerName },
  1456. { type: "text", text: "帮我 " },
  1457. {
  1458. type: "channelMention",
  1459. refId: expect.stringContaining("om_post:"),
  1460. targetId: "ou_target",
  1461. name: "Ryan Bot",
  1462. channel: providerName,
  1463. },
  1464. { type: "text", text: " 确认" },
  1465. ],
  1466. });
  1467. });
  1468. it("parses Feishu post callbacks as normal text messages", () => {
  1469. const provider = createFeishuBotProvider({
  1470. loadCredential: vi.fn(async () => "secret"),
  1471. });
  1472. expect(
  1473. provider.parseCallback({
  1474. botId: "feishu-1",
  1475. event: {
  1476. sender: { sender_id: { open_id: "ou_user" } },
  1477. message: {
  1478. chat_id: "oc_chat",
  1479. message_id: "om_post",
  1480. chat_type: "p2p",
  1481. message_type: "post",
  1482. content: JSON.stringify({
  1483. content: [
  1484. [
  1485. { tag: "at", user_id: "ou_bot", user_name: "ZCode" },
  1486. { tag: "text", text: "看看这个方案 " },
  1487. {
  1488. tag: "a",
  1489. text: "技术文档",
  1490. href: "https://example.com/doc",
  1491. },
  1492. ],
  1493. [{ tag: "text", text: "顺便总结风险" }],
  1494. ],
  1495. }),
  1496. },
  1497. },
  1498. }),
  1499. ).toEqual([
  1500. {
  1501. botId: "feishu-1",
  1502. text: "看看这个方案 技术文档 https://example.com/doc\n顺便总结风险",
  1503. actor: {
  1504. provider: "feishu",
  1505. botId: "feishu-1",
  1506. providerUserId: "ou_user",
  1507. chatType: "private",
  1508. chatId: undefined,
  1509. providerMessageId: "om_post",
  1510. },
  1511. },
  1512. ]);
  1513. });
  1514. it("parses localized Feishu post callbacks", () => {
  1515. const provider = createFeishuBotProvider({
  1516. loadCredential: vi.fn(async () => "secret"),
  1517. });
  1518. expect(
  1519. provider.parseCallback({
  1520. botId: "feishu-1",
  1521. event: {
  1522. sender: { sender_id: { open_id: "ou_user" } },
  1523. message: {
  1524. message_id: "om_i18n_post",
  1525. chat_type: "p2p",
  1526. message_type: "post",
  1527. content: JSON.stringify({
  1528. post: {
  1529. zh_cn: {
  1530. title: "标题",
  1531. content: [[{ tag: "text", text: "正文" }]],
  1532. },
  1533. },
  1534. }),
  1535. },
  1536. },
  1537. }),
  1538. ).toMatchObject([{ text: "标题\n正文" }]);
  1539. });
  1540. it("parses Lark callbacks into Lark inbound bot messages", () => {
  1541. const provider = createFeishuBotProvider({
  1542. loadCredential: vi.fn(async () => "secret"),
  1543. });
  1544. expect(
  1545. provider.parseCallback({
  1546. botId: "lark-1",
  1547. zcodeProvider: "lark",
  1548. event: {
  1549. sender: { sender_id: { open_id: "ou_user" } },
  1550. message: {
  1551. message_id: "om_message",
  1552. chat_type: "p2p",
  1553. content: JSON.stringify({ text: "/status" }),
  1554. },
  1555. },
  1556. }),
  1557. ).toEqual([
  1558. {
  1559. botId: "lark-1",
  1560. text: "/status",
  1561. actor: {
  1562. provider: "lark",
  1563. botId: "lark-1",
  1564. providerUserId: "ou_user",
  1565. chatType: "private",
  1566. chatId: undefined,
  1567. providerMessageId: "om_message",
  1568. },
  1569. },
  1570. ]);
  1571. });
  1572. it.each([
  1573. [400, 230011, { deliveryRejected: true, deliveryReplyUnavailable: true }],
  1574. [400, 230020, { deliveryRejected: true, retryAfterMs: 1000 }],
  1575. [400, 230049, { deliveryRejected: false }],
  1576. [500, undefined, { deliveryRejected: false }],
  1577. ])(
  1578. "classifies HTTP %s / code %s for safe saved-result recovery",
  1579. async (status, code, expected) => {
  1580. vi.stubGlobal(
  1581. "fetch",
  1582. vi.fn(async (url: string) =>
  1583. Response.json(
  1584. url.includes("tenant_access_token")
  1585. ? { code: 0, tenant_access_token: "token" }
  1586. : { code, msg: "test failure" },
  1587. { status: url.includes("tenant_access_token") ? 200 : status },
  1588. ),
  1589. ),
  1590. );
  1591. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1592. await expect(
  1593. provider.send(createFeishuBot({ feishuAppId: `cli_recovery_${status}_${code}` }), {
  1594. botId: "feishu-1",
  1595. provider: "feishu",
  1596. providerUserId: "oc_group",
  1597. text: "saved",
  1598. deliveryId: "saved-id",
  1599. replyToMessageId: "om_original",
  1600. }),
  1601. ).rejects.toMatchObject(expected);
  1602. },
  1603. );
  1604. it("replies to the original group input using a stable delivery uuid", async () => {
  1605. const fetchMock = vi.fn(
  1606. async (url: string) =>
  1607. new Response(
  1608. JSON.stringify(
  1609. url.includes("tenant_access_token")
  1610. ? { code: 0, tenant_access_token: "token" }
  1611. : { code: 0, data: { message_id: "om_result" } },
  1612. ),
  1613. { status: 200 },
  1614. ),
  1615. );
  1616. vi.stubGlobal("fetch", fetchMock);
  1617. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1618. await provider.send(createFeishuBot({ feishuAppId: "cli_group_delivery_test" }), {
  1619. botId: "feishu-1",
  1620. provider: "feishu",
  1621. providerUserId: "oc_group",
  1622. text: "answer",
  1623. replyToMessageId: "om_original",
  1624. deliveryId: "stable-result",
  1625. });
  1626. const call = fetchMock.mock.calls.find(([url]) => url.includes("/om_original/reply"));
  1627. expect(call).toBeDefined();
  1628. expect(JSON.parse(String((call as unknown as [string, RequestInit])[1].body))).toMatchObject({
  1629. uuid: "stable-result-0",
  1630. msg_type: "interactive",
  1631. });
  1632. });
  1633. it("rejects an explicitly referenced attachment from a different chat", async () => {
  1634. const fetchMock = vi.fn(
  1635. async (url: string) =>
  1636. new Response(
  1637. JSON.stringify(
  1638. url.includes("tenant_access_token")
  1639. ? { code: 0, tenant_access_token: "token", expire: 7200 }
  1640. : url.includes("bot/v3/info")
  1641. ? { code: 0, bot: { open_id: "ou_bot" } }
  1642. : {
  1643. code: 0,
  1644. data: {
  1645. items: [
  1646. {
  1647. message_id: "om_file",
  1648. chat_id: "oc_other",
  1649. msg_type: "file",
  1650. body: {
  1651. content: JSON.stringify({ file_key: "file_1", file_name: "a.txt" }),
  1652. },
  1653. },
  1654. ],
  1655. },
  1656. },
  1657. ),
  1658. { status: 200 },
  1659. ),
  1660. );
  1661. vi.stubGlobal("fetch", fetchMock);
  1662. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1663. await expect(
  1664. provider.prepareCallbackPayload!(
  1665. createFeishuBot({ feishuAppId: "cli_group_reference_test" }),
  1666. {
  1667. botId: "feishu-1",
  1668. event: {
  1669. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  1670. message: {
  1671. message_id: "om_input",
  1672. chat_id: "oc_a",
  1673. chat_type: "group",
  1674. parent_id: "om_file",
  1675. content: JSON.stringify({ text: "@_user_1 review" }),
  1676. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" } }],
  1677. },
  1678. },
  1679. },
  1680. ),
  1681. ).rejects.toThrow("same group");
  1682. });
  1683. it("rejects an explicitly referenced attachment from a different topic", async () => {
  1684. const fetchMock = vi.fn(
  1685. async (url: string) =>
  1686. new Response(
  1687. JSON.stringify(
  1688. url.includes("tenant_access_token")
  1689. ? { code: 0, tenant_access_token: "token", expire: 7200 }
  1690. : url.includes("bot/v3/info")
  1691. ? { code: 0, bot: { open_id: "ou_bot" } }
  1692. : {
  1693. code: 0,
  1694. data: {
  1695. items: [
  1696. {
  1697. message_id: "om_file",
  1698. chat_id: "oc_a",
  1699. thread_id: "omt_other",
  1700. msg_type: "file",
  1701. body: {
  1702. content: JSON.stringify({ file_key: "file_1", file_name: "a.txt" }),
  1703. },
  1704. },
  1705. ],
  1706. },
  1707. },
  1708. ),
  1709. { status: 200 },
  1710. ),
  1711. );
  1712. vi.stubGlobal("fetch", fetchMock);
  1713. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1714. await expect(
  1715. provider.prepareCallbackPayload!(
  1716. createFeishuBot({ feishuAppId: "cli_topic_reference_test" }),
  1717. {
  1718. botId: "feishu-1",
  1719. event: {
  1720. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  1721. message: {
  1722. message_id: "om_input",
  1723. chat_id: "oc_a",
  1724. chat_type: "group",
  1725. parent_id: "om_file",
  1726. thread_id: "omt_current",
  1727. content: JSON.stringify({ text: "@_user_1 review" }),
  1728. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" } }],
  1729. },
  1730. },
  1731. },
  1732. ),
  1733. ).rejects.toThrow("same topic");
  1734. });
  1735. it("rejects the entire rich-text input when an image reference is malformed", () => {
  1736. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1737. expect(
  1738. provider.parseCallback({
  1739. botId: "feishu-1",
  1740. zcodeBotOpenId: "ou_bot",
  1741. event: {
  1742. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  1743. message: {
  1744. chat_type: "group",
  1745. chat_id: "oc_a",
  1746. message_id: "om_invalid",
  1747. message_type: "post",
  1748. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" } }],
  1749. content: JSON.stringify({
  1750. content: [
  1751. [
  1752. { tag: "at", user_id: "ou_bot" },
  1753. { tag: "text", text: "execute partial text" },
  1754. { tag: "img" },
  1755. ],
  1756. ],
  1757. }),
  1758. },
  1759. },
  1760. }),
  1761. ).toEqual([]);
  1762. });
  1763. it("preserves inline group images and other mentions in one input", () => {
  1764. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  1765. const result = provider.parseCallback({
  1766. botId: "feishu-1",
  1767. zcodeBotOpenId: "ou_bot",
  1768. event: {
  1769. sender: { sender_type: "user", sender_id: { open_id: "ou_user" } },
  1770. message: {
  1771. chat_type: "group",
  1772. chat_id: "oc_a",
  1773. message_id: "om_post",
  1774. message_type: "post",
  1775. mentions: [{ key: "@_user_1", id: { open_id: "ou_bot" }, name: "Bot" }],
  1776. content: JSON.stringify({
  1777. content: [
  1778. [
  1779. { tag: "at", user_id: "ou_bot" },
  1780. { tag: "text", text: "review " },
  1781. { tag: "at", user_id: "ou_other", user_name: "Alice" },
  1782. { tag: "img", image_key: "img_1" },
  1783. ],
  1784. ],
  1785. }),
  1786. },
  1787. },
  1788. });
  1789. expect(result[0]?.text).toBe("@Botreview @Alice");
  1790. expect(result[0]?.commandText).toBe("review @Alice");
  1791. expect(result[0]?.attachments).toEqual([
  1792. expect.objectContaining({ kind: "image", providerFileId: "img_1" }),
  1793. ]);
  1794. });
  1795. it("parses Feishu image callbacks into attachments", () => {
  1796. const provider = createFeishuBotProvider({
  1797. loadCredential: vi.fn(async () => "secret"),
  1798. });
  1799. expect(
  1800. provider.parseCallback({
  1801. botId: "feishu-1",
  1802. event: {
  1803. sender: { sender_id: { open_id: "ou_user" } },
  1804. message: {
  1805. chat_id: "oc_chat",
  1806. message_id: "om_image",
  1807. chat_type: "p2p",
  1808. message_type: "image",
  1809. content: JSON.stringify({ image_key: "img-key-1" }),
  1810. },
  1811. },
  1812. }),
  1813. ).toEqual([
  1814. expect.objectContaining({
  1815. text: "",
  1816. attachments: [
  1817. expect.objectContaining({
  1818. kind: "image",
  1819. providerFileId: "img-key-1",
  1820. }),
  1821. ],
  1822. }),
  1823. ]);
  1824. });
  1825. it("downloads Feishu message resources with message id and file key", async () => {
  1826. const fetchMock = vi
  1827. .fn()
  1828. .mockResolvedValueOnce(
  1829. new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" })),
  1830. )
  1831. .mockResolvedValueOnce(new Response(new Uint8Array([1, 2, 3])));
  1832. vi.stubGlobal("fetch", fetchMock);
  1833. const provider = createFeishuBotProvider({
  1834. loadCredential: vi.fn(async () => "secret"),
  1835. });
  1836. await expect(
  1837. provider.downloadAttachment?.(
  1838. createFeishuBot({
  1839. id: "feishu-download",
  1840. feishuAppId: "cli_download",
  1841. credentialRef: "download-secret",
  1842. }),
  1843. {
  1844. id: "img-key-1",
  1845. kind: "image",
  1846. filename: "image.jpg",
  1847. mimeType: "image/jpeg",
  1848. providerFileId: "img-key-1",
  1849. },
  1850. {
  1851. provider: "feishu",
  1852. botId: "feishu-download",
  1853. providerUserId: "ou_user",
  1854. chatType: "private",
  1855. providerMessageId: "om_message",
  1856. },
  1857. ),
  1858. ).resolves.toEqual({
  1859. attachment: expect.objectContaining({ providerFileId: "img-key-1" }),
  1860. data: new Uint8Array([1, 2, 3]),
  1861. });
  1862. expect(String(fetchMock.mock.calls[1]?.[0])).toContain(
  1863. "/im/v1/messages/om_message/resources/img-key-1?type=image",
  1864. );
  1865. });
  1866. it("parses Feishu card actions in private chats when context includes a chat id", () => {
  1867. const provider = createFeishuBotProvider({
  1868. loadCredential: vi.fn(async () => "secret"),
  1869. });
  1870. expect(
  1871. provider.parseCallback({
  1872. botId: "feishu-1",
  1873. event_type: "card.action.trigger",
  1874. operator: { operator_id: { open_id: "ou_user" } },
  1875. action: { value: { command: "/model provider custom:test" } },
  1876. context: { open_chat_id: "oc_context" },
  1877. }),
  1878. ).toEqual([
  1879. {
  1880. botId: "feishu-1",
  1881. text: "/model provider custom:test",
  1882. actor: {
  1883. provider: "feishu",
  1884. botId: "feishu-1",
  1885. providerUserId: "ou_user",
  1886. chatType: "private",
  1887. },
  1888. },
  1889. ]);
  1890. });
  1891. it("parses Feishu card actions from nested event payloads", () => {
  1892. const provider = createFeishuBotProvider({
  1893. loadCredential: vi.fn(async () => "secret"),
  1894. });
  1895. expect(
  1896. provider.parseCallback({
  1897. botId: "feishu-1",
  1898. header: { event_type: "card.action.trigger" },
  1899. event: {
  1900. event_id: "feishu-card-event-1",
  1901. operator: { operator_id: { open_id: "ou_user" } },
  1902. action: { value: { command: "/cancel" }, token: "card-token" },
  1903. context: { open_chat_id: "oc_context" },
  1904. },
  1905. }),
  1906. ).toMatchObject([
  1907. {
  1908. text: "/cancel",
  1909. actor: { providerMessageId: "feishu-card-event-1" },
  1910. },
  1911. ]);
  1912. });
  1913. it("parses Feishu card actions from schema 2 behavior values", () => {
  1914. const provider = createFeishuBotProvider({
  1915. loadCredential: vi.fn(async () => "secret"),
  1916. });
  1917. expect(
  1918. provider.parseCallback({
  1919. botId: "feishu-1",
  1920. header: { event_type: "card.action.trigger" },
  1921. event: {
  1922. event_id: "feishu-card-event-2",
  1923. operator: { operator_id: { open_id: "ou_user" } },
  1924. action: {
  1925. behaviors: [
  1926. {
  1927. type: "callback",
  1928. value: { command: "/workspace /tmp/workspace" },
  1929. },
  1930. ],
  1931. },
  1932. context: { open_chat_id: "oc_context" },
  1933. },
  1934. }),
  1935. ).toMatchObject([
  1936. {
  1937. text: "/workspace /tmp/workspace",
  1938. actor: { providerMessageId: "feishu-card-event-2" },
  1939. },
  1940. ]);
  1941. });
  1942. it("parses legacy Feishu card actions with top-level open_id", () => {
  1943. const provider = createFeishuBotProvider({
  1944. loadCredential: vi.fn(async () => "secret"),
  1945. });
  1946. expect(
  1947. provider.parseCallback({
  1948. botId: "feishu-1",
  1949. open_id: "ou_user",
  1950. action: { value: { command: "/status" } },
  1951. }),
  1952. ).toEqual([
  1953. {
  1954. botId: "feishu-1",
  1955. text: "/status",
  1956. actor: {
  1957. provider: "feishu",
  1958. botId: "feishu-1",
  1959. providerUserId: "ou_user",
  1960. chatType: "private",
  1961. },
  1962. },
  1963. ]);
  1964. });
  1965. it("marks explicit group card callbacks for authorization", () => {
  1966. const provider = createFeishuBotProvider({
  1967. loadCredential: vi.fn(async () => "secret"),
  1968. });
  1969. expect(
  1970. provider.parseCallback({
  1971. botId: "feishu-1",
  1972. event_type: "card.action.trigger",
  1973. operator: { operator_id: { open_id: "ou_user" } },
  1974. action: { value: { command: "/status" } },
  1975. context: { chat_type: "group_chat", open_chat_id: "oc_group" },
  1976. }),
  1977. ).toEqual([
  1978. {
  1979. botId: "feishu-1",
  1980. groupCardAction: true,
  1981. text: "/status",
  1982. actor: {
  1983. provider: "feishu",
  1984. botId: "feishu-1",
  1985. providerUserId: "ou_user",
  1986. chatType: "group",
  1987. chatId: "oc_group",
  1988. },
  1989. },
  1990. ]);
  1991. });
  1992. it("sends text messages through Feishu markdown cards", async () => {
  1993. const fetchMock = vi.fn(async (url: string) => {
  1994. if (url.endsWith("/tenant_access_token/internal")) {
  1995. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  1996. }
  1997. return new Response(JSON.stringify({ code: 0 }));
  1998. });
  1999. vi.stubGlobal("fetch", fetchMock);
  2000. const provider = createFeishuBotProvider({
  2001. loadCredential: vi.fn(async () => "app-secret-value"),
  2002. });
  2003. await provider.send(createFeishuBot(), {
  2004. botId: "feishu-1",
  2005. provider: "feishu",
  2006. providerUserId: "oc_chat",
  2007. text: "**hello**",
  2008. });
  2009. expect(fetchMock).toHaveBeenCalledTimes(2);
  2010. expect(String(fetchMock.mock.calls[1]?.[0])).toContain("receive_id_type=chat_id");
  2011. const body = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body)) as {
  2012. receive_id?: string;
  2013. msg_type?: string;
  2014. content?: string;
  2015. };
  2016. expect(body.receive_id).toBe("oc_chat");
  2017. expect(body.msg_type).toBe("interactive");
  2018. expect(parseFeishuCardContent(body.content)).toMatchObject({
  2019. schema: "2.0",
  2020. body: {
  2021. elements: [
  2022. {
  2023. tag: "markdown",
  2024. content: "**hello**",
  2025. },
  2026. ],
  2027. },
  2028. });
  2029. });
  2030. it("keeps multiline status replies readable in Feishu schema 2 cards", async () => {
  2031. const fetchMock = vi.fn(async (url: string) => {
  2032. if (url.endsWith("/tenant_access_token/internal")) {
  2033. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2034. }
  2035. return new Response(JSON.stringify({ code: 0 }));
  2036. });
  2037. vi.stubGlobal("fetch", fetchMock);
  2038. const provider = createFeishuBotProvider({
  2039. loadCredential: vi.fn(async () => "app-secret-value"),
  2040. });
  2041. await provider.send(createFeishuBot(), {
  2042. botId: "feishu-1",
  2043. provider: "feishu",
  2044. providerUserId: "oc_chat",
  2045. text: [
  2046. "Workspace: z-code",
  2047. "Model: DeepSeek/deepseek-v4-flash",
  2048. "------",
  2049. "Task: 你好啊 (sess_1)",
  2050. "State: completed",
  2051. "Worked: 1s",
  2052. ].join("\n"),
  2053. });
  2054. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2055. String(url).includes("/open-apis/im/v1/messages"),
  2056. );
  2057. const body = JSON.parse(String(sendCall?.[1]?.body)) as {
  2058. content?: string;
  2059. };
  2060. expect(parseFeishuCardContent(body.content)).toMatchObject({
  2061. schema: "2.0",
  2062. body: {
  2063. elements: [
  2064. {
  2065. tag: "markdown",
  2066. content: [
  2067. "Workspace: z-code ",
  2068. "Model: DeepSeek/deepseek-v4-flash",
  2069. "",
  2070. "---",
  2071. "",
  2072. "Task: 你好啊 (sess_1) ",
  2073. "State: completed ",
  2074. "Worked: 1s",
  2075. ].join("\n"),
  2076. },
  2077. ],
  2078. },
  2079. });
  2080. });
  2081. it("uses the Lark OpenAPI domain for Lark bots", async () => {
  2082. const fetchMock = vi.fn(async (url: string) => {
  2083. if (url.endsWith("/tenant_access_token/internal")) {
  2084. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2085. }
  2086. return new Response(JSON.stringify({ code: 0 }));
  2087. });
  2088. vi.stubGlobal("fetch", fetchMock);
  2089. const provider = createFeishuBotProvider({
  2090. loadCredential: vi.fn(async () => "app-secret-value"),
  2091. });
  2092. await provider.send(createFeishuBot({ provider: "lark", id: "lark-1" }), {
  2093. botId: "lark-1",
  2094. provider: "lark",
  2095. providerUserId: "ou_user",
  2096. text: "hello",
  2097. });
  2098. expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
  2099. "https://open.larksuite.com/open-apis/auth/v3/tenant_access_token/internal",
  2100. );
  2101. expect(String(fetchMock.mock.calls[1]?.[0])).toContain(
  2102. "https://open.larksuite.com/open-apis/im/v1/messages",
  2103. );
  2104. });
  2105. it("creates and updates Feishu streaming reply cards with collapsed tool summaries", async () => {
  2106. const fetchMock = vi.fn(async (url: string) => {
  2107. if (url.endsWith("/tenant_access_token/internal")) {
  2108. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2109. }
  2110. if (String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id")) {
  2111. return new Response(JSON.stringify({ code: 0, data: { message_id: "om_streaming" } }));
  2112. }
  2113. return new Response(JSON.stringify({ code: 0 }));
  2114. });
  2115. vi.stubGlobal("fetch", fetchMock);
  2116. const provider = createFeishuBotProvider({
  2117. loadCredential: vi.fn(async () => "app-secret-value"),
  2118. });
  2119. const handle = await provider.createStreamingReplyCard?.(createFeishuBot(), {
  2120. providerUserId: "ou_user",
  2121. blocks: [
  2122. { type: "message", text: "正在检查项目" },
  2123. {
  2124. type: "tools",
  2125. title: "工具摘要",
  2126. summaries: ["- 完成 · Read `README.md`"],
  2127. expanded: true,
  2128. },
  2129. ],
  2130. status: "running",
  2131. });
  2132. await provider.updateStreamingReplyCard?.(createFeishuBot(), handle!, {
  2133. providerUserId: "ou_user",
  2134. blocks: [
  2135. { type: "message", text: "正在检查项目" },
  2136. {
  2137. type: "tools",
  2138. title: "工具摘要",
  2139. summaries: ["- 完成 · Read `README.md`"],
  2140. expanded: false,
  2141. },
  2142. { type: "message", text: "检查完成" },
  2143. {
  2144. type: "tools",
  2145. title: "工具摘要",
  2146. summaries: ["- 完成 · Bash `pnpm test`"],
  2147. expanded: false,
  2148. },
  2149. ],
  2150. status: "completed",
  2151. });
  2152. expect(handle).toEqual({ providerMessageId: "om_streaming" });
  2153. const createCall = fetchMock.mock.calls.find(([url]) =>
  2154. String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id"),
  2155. );
  2156. const createBody = JSON.parse(String(createCall?.[1]?.body)) as { content?: string };
  2157. const createCard = parseFeishuCardContent(createBody.content);
  2158. expect(createCard).toMatchObject({
  2159. schema: "2.0",
  2160. body: {
  2161. elements: [
  2162. { tag: "markdown", content: "正在检查项目" },
  2163. {
  2164. tag: "collapsible_panel",
  2165. expanded: true,
  2166. background_color: "grey-50",
  2167. border: { color: "grey", corner_radius: "8px" },
  2168. header: {
  2169. title: { tag: "plain_text", content: "🛠️ 工具摘要 (1)" },
  2170. vertical_align: "center",
  2171. icon: {
  2172. tag: "standard_icon",
  2173. token: "down-small-ccm_outlined",
  2174. color: "grey",
  2175. size: "16px 16px",
  2176. },
  2177. icon_position: "right",
  2178. icon_expanded_angle: -180,
  2179. },
  2180. },
  2181. { tag: "markdown", content: "⏳ 运行中" },
  2182. ],
  2183. },
  2184. });
  2185. expect(JSON.stringify(createCard)).not.toContain("input");
  2186. const updateCall = fetchMock.mock.calls.find(([url]) =>
  2187. String(url).includes("/open-apis/im/v1/messages/om_streaming"),
  2188. );
  2189. expect(String(updateCall?.[0])).toContain("/open-apis/im/v1/messages/om_streaming");
  2190. expect(updateCall?.[1]?.method).toBe("PATCH");
  2191. const updateBody = JSON.parse(String(updateCall?.[1]?.body)) as { content?: string };
  2192. const updateCard = parseFeishuCardContent(updateBody.content);
  2193. expect(updateCard).toMatchObject({
  2194. schema: "2.0",
  2195. body: {
  2196. elements: expect.arrayContaining([
  2197. expect.objectContaining({
  2198. tag: "collapsible_panel",
  2199. expanded: false,
  2200. }),
  2201. ]),
  2202. },
  2203. });
  2204. const updateCardJson = JSON.stringify(updateCard);
  2205. expect(updateCardJson.match(/🛠️ 工具摘要 \(1\)/gu) ?? []).toHaveLength(2);
  2206. expect(updateCardJson).toContain("检查完成");
  2207. expect(updateCardJson).toContain("✅ 已完成");
  2208. });
  2209. it("resolves the Feishu bot name from application info API", async () => {
  2210. const fetchMock = vi.fn(async (url: string) => {
  2211. if (url.endsWith("/tenant_access_token/internal")) {
  2212. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2213. }
  2214. if (url.endsWith("/application/v6/applications/cli_name?lang=zh_cn")) {
  2215. return new Response(
  2216. JSON.stringify({
  2217. code: 0,
  2218. data: {
  2219. app: {
  2220. app_name: "ZCode Assistant",
  2221. },
  2222. },
  2223. }),
  2224. );
  2225. }
  2226. return new Response(JSON.stringify({ code: 999, msg: "unexpected request" }));
  2227. });
  2228. vi.stubGlobal("fetch", fetchMock);
  2229. const provider = createFeishuBotProvider({
  2230. loadCredential: vi.fn(async () => "app-secret-value"),
  2231. });
  2232. await expect(
  2233. provider.resolveName?.({
  2234. ...createFeishuBot(),
  2235. credentialRef: "app-secret-name",
  2236. feishuAppId: "cli_name",
  2237. }),
  2238. ).resolves.toBe("ZCode Assistant");
  2239. expect(fetchMock).toHaveBeenCalledTimes(2);
  2240. expect(String(fetchMock.mock.calls[1]?.[0])).toContain(
  2241. "/open-apis/application/v6/applications/cli_name?lang=zh_cn",
  2242. );
  2243. expect(fetchMock.mock.calls[1]?.[1]?.headers).toEqual({ authorization: "Bearer tenant-token" });
  2244. });
  2245. it("falls back to the current Feishu app when app id info is not ready", async () => {
  2246. const fetchMock = vi.fn(async (url: string) => {
  2247. if (url.endsWith("/tenant_access_token/internal")) {
  2248. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2249. }
  2250. if (url.endsWith("/application/v6/applications/cli_fallback?lang=zh_cn")) {
  2251. return new Response(JSON.stringify({ code: 999, msg: "not ready" }));
  2252. }
  2253. if (url.endsWith("/application/v6/applications/me?lang=zh_cn")) {
  2254. return new Response(
  2255. JSON.stringify({
  2256. code: 0,
  2257. data: {
  2258. app: {
  2259. app_name: "ZCode Assistant",
  2260. },
  2261. },
  2262. }),
  2263. );
  2264. }
  2265. return new Response(JSON.stringify({ code: 999, msg: "unexpected request" }));
  2266. });
  2267. vi.stubGlobal("fetch", fetchMock);
  2268. const provider = createFeishuBotProvider({
  2269. loadCredential: vi.fn(async () => "app-secret-value"),
  2270. });
  2271. await expect(
  2272. provider.resolveName?.({
  2273. ...createFeishuBot(),
  2274. credentialRef: "app-secret-name",
  2275. feishuAppId: "cli_fallback",
  2276. }),
  2277. ).resolves.toBe("ZCode Assistant");
  2278. expect(fetchMock).toHaveBeenCalledTimes(3);
  2279. expect(String(fetchMock.mock.calls[2]?.[0])).toContain(
  2280. "/open-apis/application/v6/applications/me?lang=zh_cn",
  2281. );
  2282. });
  2283. it.each(["feishu", "lark"] as const)(
  2284. "resolves %s group actors through the chat directory",
  2285. async (domain) => {
  2286. const fetchMock = vi.fn(async (url: string) => {
  2287. if (url.endsWith("/tenant_access_token/internal"))
  2288. return new Response(JSON.stringify({ code: 0, tenant_access_token: "member-token" }));
  2289. expect(url).toContain(domain === "lark" ? "open.larksuite.com" : "open.feishu.cn");
  2290. expect(url).toContain("/im/v1/chats/oc_directory/members?");
  2291. expect(url).toContain("member_id_type=open_id");
  2292. return new Response(
  2293. JSON.stringify({
  2294. code: 0,
  2295. data: { items: [{ member_id: "ou_member", name: "Alice" }], has_more: false },
  2296. }),
  2297. );
  2298. });
  2299. vi.stubGlobal("fetch", fetchMock);
  2300. const provider = createFeishuBotProvider({ loadCredential: vi.fn(async () => "secret") });
  2301. const bot = createFeishuBot({ provider: domain, feishuAppId: `cli_directory_${domain}` });
  2302. expect(
  2303. await provider.resolveActorDisplayName!(bot, {
  2304. botId: bot.id,
  2305. provider: domain,
  2306. providerUserId: "ou_member",
  2307. chatType: "group",
  2308. chatId: "oc_directory",
  2309. }),
  2310. ).toBe("Alice");
  2311. expect(await provider.getGroupMemberNames!(bot, "oc_directory")).toEqual({
  2312. ou_member: "Alice",
  2313. });
  2314. expect(fetchMock).toHaveBeenCalledTimes(2);
  2315. },
  2316. );
  2317. it("resolves Feishu actor display names from the contact API", async () => {
  2318. const fetchMock = vi.fn(async (url: string) => {
  2319. if (url.endsWith("/tenant_access_token/internal")) {
  2320. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2321. }
  2322. if (url.includes("/open-apis/contact/v3/users/ou_user?user_id_type=open_id")) {
  2323. return new Response(
  2324. JSON.stringify({
  2325. code: 0,
  2326. data: {
  2327. user: {
  2328. name: "张三",
  2329. },
  2330. },
  2331. }),
  2332. );
  2333. }
  2334. return new Response(JSON.stringify({ code: 999, msg: "unexpected request" }));
  2335. });
  2336. vi.stubGlobal("fetch", fetchMock);
  2337. const provider = createFeishuBotProvider({
  2338. loadCredential: vi.fn(async () => "app-secret-value"),
  2339. });
  2340. await expect(
  2341. provider.resolveActorDisplayName?.(
  2342. createFeishuBot({
  2343. credentialRef: "app-secret-actor-name",
  2344. feishuAppId: "cli_actor_name",
  2345. }),
  2346. {
  2347. botId: "feishu-1",
  2348. provider: "feishu",
  2349. providerUserId: "ou_user",
  2350. chatType: "private",
  2351. },
  2352. ),
  2353. ).resolves.toBe("张三");
  2354. expect(fetchMock).toHaveBeenCalledTimes(2);
  2355. expect(fetchMock.mock.calls[1]?.[1]?.headers).toEqual({ authorization: "Bearer tenant-token" });
  2356. });
  2357. it("sends selection prompts as Feishu interactive cards", async () => {
  2358. const fetchMock = vi.fn(async (url: string) => {
  2359. if (url.endsWith("/tenant_access_token/internal")) {
  2360. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2361. }
  2362. return new Response(JSON.stringify({ code: 0 }));
  2363. });
  2364. vi.stubGlobal("fetch", fetchMock);
  2365. const provider = createFeishuBotProvider({
  2366. loadCredential: vi.fn(async () => "app-secret-value"),
  2367. });
  2368. await provider.send(createFeishuBot(), {
  2369. botId: "feishu-1",
  2370. provider: "feishu",
  2371. providerUserId: "ou_user",
  2372. text: "Select",
  2373. selection: {
  2374. id: "workspace",
  2375. title: "Workspace",
  2376. cancelLabel: "Cancel",
  2377. action: "workspace.set",
  2378. options: [{ id: "/workspace workspace-1", label: "Workspace" }],
  2379. },
  2380. });
  2381. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2382. String(url).includes("/open-apis/im/v1/messages"),
  2383. );
  2384. const body = JSON.parse(String(sendCall?.[1]?.body)) as { msg_type?: string; content?: string };
  2385. expect(body.msg_type).toBe("interactive");
  2386. const card = parseFeishuCardContent(body.content);
  2387. expect(card).toMatchObject({
  2388. schema: "2.0",
  2389. body: {
  2390. elements: [
  2391. { tag: "markdown", content: "Select" },
  2392. {
  2393. tag: "button",
  2394. text: { tag: "plain_text", content: "Workspace" },
  2395. behaviors: [
  2396. {
  2397. value: { command: "/workspace /workspace workspace-1" },
  2398. type: "callback",
  2399. },
  2400. ],
  2401. },
  2402. {
  2403. tag: "button",
  2404. text: { tag: "plain_text", content: "Cancel" },
  2405. behaviors: [
  2406. {
  2407. value: { command: "/cancel" },
  2408. type: "callback",
  2409. },
  2410. ],
  2411. },
  2412. ],
  2413. },
  2414. });
  2415. expect(JSON.stringify(card)).not.toContain('"tag":"action"');
  2416. expect(JSON.stringify(card)).not.toContain('"actions"');
  2417. });
  2418. it.each([200, 400])(
  2419. "reports message delivery failure and recovery for HTTP %s",
  2420. async (status) => {
  2421. let failed = true;
  2422. const fetchMock = vi.fn(async (url: string) => {
  2423. if (url.endsWith("/tenant_access_token/internal")) {
  2424. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2425. }
  2426. return new Response(
  2427. JSON.stringify(
  2428. failed
  2429. ? {
  2430. code: 230101,
  2431. msg: "Sending messages to users is temporarily unavailable.",
  2432. error: { log_id: "delivery-log" },
  2433. }
  2434. : { code: 0, data: { message_id: "om_delivered" } },
  2435. ),
  2436. { status: failed ? status : 200 },
  2437. );
  2438. });
  2439. vi.stubGlobal("fetch", fetchMock);
  2440. const onDeliveryResult = vi.fn();
  2441. const provider = createFeishuBotProvider({
  2442. loadCredential: async () => "secret",
  2443. onDeliveryResult,
  2444. });
  2445. const bot = createFeishuBot();
  2446. const message = {
  2447. botId: bot.id,
  2448. provider: bot.provider,
  2449. providerUserId: "ou_user",
  2450. text: "test",
  2451. };
  2452. await expect(provider.send(bot, message)).rejects.toThrow(`HTTP ${status}, code=230101`);
  2453. expect(onDeliveryResult).toHaveBeenLastCalledWith(
  2454. bot,
  2455. expect.stringContaining("log_id=delivery-log"),
  2456. );
  2457. expect(onDeliveryResult).toHaveBeenLastCalledWith(
  2458. bot,
  2459. expect.stringContaining("receive_id_type=open_id"),
  2460. );
  2461. failed = false;
  2462. await provider.send(bot, message);
  2463. expect(onDeliveryResult).toHaveBeenLastCalledWith(bot, undefined);
  2464. },
  2465. );
  2466. it("preserves update business errors and falls back to the response log header", async () => {
  2467. vi.stubGlobal(
  2468. "fetch",
  2469. vi.fn(async (url: string) =>
  2470. url.endsWith("/tenant_access_token/internal")
  2471. ? new Response(JSON.stringify({ code: 0, tenant_access_token: "token" }))
  2472. : new Response(JSON.stringify({ code: 230101, msg: "Delivery rejected" }), {
  2473. headers: { "x-tt-logid": "header-log" },
  2474. }),
  2475. ),
  2476. );
  2477. const onDeliveryResult = vi.fn();
  2478. const bot = createFeishuBot();
  2479. const provider = createFeishuBotProvider({
  2480. loadCredential: async () => "secret",
  2481. onDeliveryResult,
  2482. });
  2483. await expect(
  2484. provider.updateTransientInteractionCard!(
  2485. bot,
  2486. { providerMessageId: "om_card" },
  2487. {
  2488. botId: bot.id,
  2489. provider: bot.provider,
  2490. providerUserId: "ou_user",
  2491. text: "reply",
  2492. },
  2493. ),
  2494. ).rejects.toThrow("HTTP 200, code=230101, msg=Delivery rejected, log_id=header-log");
  2495. expect(onDeliveryResult).toHaveBeenCalledWith(bot, expect.stringContaining("header-log"));
  2496. });
  2497. it("preserves Feishu business error details when sending a card returns HTTP 400", async () => {
  2498. const fetchMock = vi.fn(async (url: string) => {
  2499. if (url.endsWith("/tenant_access_token/internal")) {
  2500. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2501. }
  2502. return new Response(
  2503. JSON.stringify({
  2504. code: 230013,
  2505. msg: "Bot has NO availability to this user.",
  2506. error: { log_id: "20260805113649ABCDEF" },
  2507. }),
  2508. { status: 400 },
  2509. );
  2510. });
  2511. vi.stubGlobal("fetch", fetchMock);
  2512. const provider = createFeishuBotProvider({
  2513. loadCredential: vi.fn(async () => "app-secret-value"),
  2514. });
  2515. await expect(
  2516. provider.send(createFeishuBot(), {
  2517. botId: "feishu-1",
  2518. provider: "feishu",
  2519. providerUserId: "ou_user",
  2520. text: "Help",
  2521. }),
  2522. ).rejects.toThrow(
  2523. "Feishu send interactive message failed: HTTP 400, code=230013, msg=Bot has NO availability to this user., log_id=20260805113649ABCDEF",
  2524. );
  2525. });
  2526. it("sends elicitation options as Feishu elicitation commands", async () => {
  2527. const fetchMock = vi.fn(async (url: string) => {
  2528. if (url.endsWith("/tenant_access_token/internal")) {
  2529. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2530. }
  2531. return new Response(JSON.stringify({ code: 0 }));
  2532. });
  2533. vi.stubGlobal("fetch", fetchMock);
  2534. const provider = createFeishuBotProvider({
  2535. loadCredential: vi.fn(async () => "app-secret-value"),
  2536. });
  2537. await provider.send(createFeishuBot(), {
  2538. botId: "feishu-1",
  2539. provider: "feishu",
  2540. providerUserId: "ou_user",
  2541. text: "Ask",
  2542. selection: {
  2543. id: "elicitation-1",
  2544. token: "abc123def456",
  2545. title: "Ask",
  2546. action: "elicitation.respond",
  2547. options: [{ id: "fast path", label: "Fast" }],
  2548. },
  2549. });
  2550. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2551. String(url).includes("/open-apis/im/v1/messages"),
  2552. );
  2553. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  2554. expect(parseFeishuCardContent(body.content)).toMatchObject({
  2555. schema: "2.0",
  2556. body: {
  2557. elements: expect.arrayContaining([
  2558. expect.objectContaining({
  2559. tag: "button",
  2560. behaviors: [
  2561. expect.objectContaining({
  2562. value: { command: "/elicitation abc123def456 fast path", zcodeCardText: "Ask" },
  2563. }),
  2564. ],
  2565. }),
  2566. ]),
  2567. },
  2568. });
  2569. });
  2570. it("renders ExitPlanMode as a plan approval card instead of a generic question", async () => {
  2571. const fetchMock = vi.fn(async (url: string) => {
  2572. if (url.endsWith("/tenant_access_token/internal")) {
  2573. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2574. }
  2575. return new Response(JSON.stringify({ code: 0 }));
  2576. });
  2577. vi.stubGlobal("fetch", fetchMock);
  2578. const provider = createFeishuBotProvider({
  2579. loadCredential: vi.fn(async () => "app-secret-value"),
  2580. });
  2581. await provider.send(createFeishuBot(), {
  2582. botId: "feishu-1",
  2583. provider: "feishu",
  2584. providerUserId: "ou_user",
  2585. text: "Review this implementation plan.",
  2586. locale: "zh-CN",
  2587. elicitation: {
  2588. requestId: "plan-1",
  2589. taskId: "task-1",
  2590. runId: "run-1",
  2591. currentQuestionIndex: 0,
  2592. questions: [
  2593. {
  2594. question: "Review this implementation plan.",
  2595. header: "Implementation plan",
  2596. options: [
  2597. {
  2598. value: "approve",
  2599. label: "Approve",
  2600. description: "Exit plan mode and start implementation.",
  2601. },
  2602. ],
  2603. },
  2604. ],
  2605. status: "pending",
  2606. schema: {
  2607. interaction: "plan_approval",
  2608. toolName: "ExitPlanMode",
  2609. plan: "# Snake game\n\n1. Create Vite project\n2. Implement gameplay",
  2610. },
  2611. },
  2612. selection: {
  2613. id: "elicitation-plan-1-0",
  2614. token: "abc123def456",
  2615. title: "Review this implementation plan.",
  2616. action: "elicitation.respond",
  2617. options: [
  2618. {
  2619. id: "approve",
  2620. label: "批准",
  2621. description: "退出计划模式并开始实施。",
  2622. },
  2623. ],
  2624. },
  2625. });
  2626. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2627. String(url).includes("/open-apis/im/v1/messages"),
  2628. );
  2629. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  2630. const cardJson = JSON.stringify(parseFeishuCardContent(body.content));
  2631. expect(cardJson).toContain("**请审阅此实施计划。**");
  2632. expect(cardJson).not.toContain("**Review this implementation plan.**");
  2633. expect(cardJson).toContain("# Snake game");
  2634. expect(cardJson).toContain("Implement gameplay");
  2635. expect(cardJson).toContain("批准");
  2636. expect(cardJson).toContain("自定义回答");
  2637. expect(cardJson).not.toContain("#### 提问");
  2638. expect(cardJson).not.toContain("退出计划模式并开始实施。");
  2639. const planIndex = cardJson.indexOf("# Snake game");
  2640. const dividerIndex = cardJson.indexOf('"tag":"hr"');
  2641. const reviewIndex = cardJson.indexOf("**请审阅此实施计划。**");
  2642. expect(planIndex).toBeGreaterThan(-1);
  2643. expect(dividerIndex).toBeGreaterThan(planIndex);
  2644. expect(reviewIndex).toBeGreaterThan(dividerIndex);
  2645. });
  2646. it("localizes the ExitPlanMode review title for English Feishu cards", async () => {
  2647. const fetchMock = vi.fn(async (url: string) => {
  2648. if (url.endsWith("/tenant_access_token/internal")) {
  2649. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2650. }
  2651. return new Response(JSON.stringify({ code: 0 }));
  2652. });
  2653. vi.stubGlobal("fetch", fetchMock);
  2654. const provider = createFeishuBotProvider({
  2655. loadCredential: vi.fn(async () => "app-secret-value"),
  2656. });
  2657. await provider.send(createFeishuBot(), {
  2658. botId: "feishu-1",
  2659. provider: "feishu",
  2660. providerUserId: "ou_user",
  2661. text: "Review this implementation plan.",
  2662. locale: "en-US",
  2663. elicitation: {
  2664. requestId: "plan-en-1",
  2665. taskId: "task-1",
  2666. runId: "run-1",
  2667. currentQuestionIndex: 0,
  2668. questions: [
  2669. {
  2670. question: "Review this implementation plan.",
  2671. options: [{ value: "approve", label: "Approve" }],
  2672. },
  2673. ],
  2674. status: "pending",
  2675. schema: { interaction: "plan_approval", toolName: "ExitPlanMode", plan: "1. Ship it" },
  2676. },
  2677. selection: {
  2678. id: "elicitation-plan-en-1-0",
  2679. token: "abc123def456",
  2680. title: "Review this implementation plan.",
  2681. action: "elicitation.respond",
  2682. options: [{ id: "approve", label: "Approve" }],
  2683. },
  2684. });
  2685. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2686. String(url).includes("/open-apis/im/v1/messages"),
  2687. );
  2688. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  2689. const cardJson = JSON.stringify(parseFeishuCardContent(body.content));
  2690. expect(cardJson).toContain("**Review this implementation plan.**");
  2691. expect(cardJson).not.toContain("请审阅此实施计划。");
  2692. });
  2693. it("renders AskUserQuestion answers and multi-select actions in one Feishu card", async () => {
  2694. const fetchMock = vi.fn(async (url: string) => {
  2695. if (url.endsWith("/tenant_access_token/internal")) {
  2696. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2697. }
  2698. return new Response(JSON.stringify({ code: 0 }));
  2699. });
  2700. vi.stubGlobal("fetch", fetchMock);
  2701. const provider = createFeishuBotProvider({
  2702. loadCredential: vi.fn(async () => "app-secret-value"),
  2703. });
  2704. await provider.send(createFeishuBot(), {
  2705. botId: "feishu-1",
  2706. provider: "feishu",
  2707. providerUserId: "ou_user",
  2708. text: "Question",
  2709. elicitation: {
  2710. requestId: "ask-1",
  2711. taskId: "task-1",
  2712. runId: "run-1",
  2713. currentQuestionIndex: 1,
  2714. questions: [
  2715. {
  2716. question: "你想在哪里运行贪吃蛇游戏?",
  2717. options: [{ value: "web", label: "网页版 (HTML/CSS/JS)" }],
  2718. },
  2719. {
  2720. question: "你希望游戏有什么功能?",
  2721. options: [
  2722. { value: "base", label: "基础玩法" },
  2723. { value: "score", label: "分数系统" },
  2724. ],
  2725. multiSelect: true,
  2726. },
  2727. ],
  2728. answers: { "0": ["web"], "1": ["base"] },
  2729. status: "pending",
  2730. },
  2731. selection: {
  2732. id: "elicitation-ask-1-1",
  2733. token: "abc123def456",
  2734. title: "Question",
  2735. action: "elicitation.respond",
  2736. options: [
  2737. { id: "base", label: "[x] 基础玩法" },
  2738. { id: "score", label: "[ ] 分数系统" },
  2739. { id: "__submit__", label: "完成" },
  2740. ],
  2741. },
  2742. });
  2743. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2744. String(url).includes("/open-apis/im/v1/messages"),
  2745. );
  2746. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  2747. const card = parseFeishuCardContent(body.content);
  2748. const cardJson = JSON.stringify(card);
  2749. expect(card).toMatchObject({ schema: "2.0" });
  2750. expect(cardJson).toContain("#### 1/2 你想在哪里运行贪吃蛇游戏?");
  2751. expect(cardJson).toContain("网页版 (HTML/CSS/JS)");
  2752. expect(cardJson).toContain('"tag":"hr"');
  2753. expect(cardJson).not.toContain('"content":"---\\n"');
  2754. expect(cardJson).toContain("#### 提问");
  2755. expect(cardJson).toContain("你希望游戏有什么功能?");
  2756. expect(cardJson).toContain('"tag":"form"');
  2757. expect(cardJson).toContain("☑ 基础玩法");
  2758. expect(cardJson).toContain("☐ 分数系统");
  2759. expect(cardJson).toContain("☐ 自定义回答");
  2760. // 当前题的“基础玩法”只应存在于待回答区的选中按钮,不能提前进入已回答历史。
  2761. expect(cardJson.match(/基础玩法/gu)).toHaveLength(1);
  2762. expect(cardJson.indexOf("你想在哪里运行贪吃蛇游戏?")).toBeLessThan(
  2763. cardJson.indexOf('"tag":"hr"'),
  2764. );
  2765. expect(cardJson.indexOf('"tag":"hr"')).toBeLessThan(cardJson.indexOf("你希望游戏有什么功能?"));
  2766. expect(cardJson).not.toContain('"tag":"input"');
  2767. expect(cardJson).not.toContain('"tag":"multi_select_static"');
  2768. expect(cardJson).toContain("/elicitation abc123def456 __form__:");
  2769. expect(cardJson).not.toContain("__submit__");
  2770. });
  2771. it("renders free-text AskUserQuestion as a Feishu form input", async () => {
  2772. const fetchMock = vi.fn(async (url: string) => {
  2773. if (url.endsWith("/tenant_access_token/internal")) {
  2774. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2775. }
  2776. return new Response(JSON.stringify({ code: 0 }));
  2777. });
  2778. vi.stubGlobal("fetch", fetchMock);
  2779. const provider = createFeishuBotProvider({
  2780. loadCredential: vi.fn(async () => "app-secret-value"),
  2781. });
  2782. await provider.send(createFeishuBot(), {
  2783. botId: "feishu-1",
  2784. provider: "feishu",
  2785. providerUserId: "ou_user",
  2786. text: "Question",
  2787. elicitation: {
  2788. requestId: "ask-text",
  2789. taskId: "task-1",
  2790. runId: "run-1",
  2791. currentQuestionIndex: 0,
  2792. questions: [
  2793. {
  2794. question: "请补充需求说明",
  2795. options: [],
  2796. },
  2797. ],
  2798. answers: {},
  2799. status: "pending",
  2800. },
  2801. selection: {
  2802. id: "elicitation-ask-text-0",
  2803. token: "abc123def456",
  2804. title: "Question",
  2805. action: "elicitation.respond",
  2806. options: [],
  2807. },
  2808. });
  2809. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2810. String(url).includes("/open-apis/im/v1/messages"),
  2811. );
  2812. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  2813. const cardJson = JSON.stringify(parseFeishuCardContent(body.content));
  2814. expect(cardJson).toContain("#### 提问");
  2815. expect(cardJson).toContain("请补充需求说明");
  2816. expect(cardJson).toContain("自定义回答");
  2817. expect(cardJson).toContain('"tag":"input"');
  2818. expect(cardJson).toContain('"input_type":"multiline_text"');
  2819. expect(cardJson).toContain("/elicitation abc123def456 __form__:");
  2820. });
  2821. it("renders single-select AskUserQuestion as flat radio choices", async () => {
  2822. const fetchMock = vi.fn(async (url: string) => {
  2823. if (url.endsWith("/tenant_access_token/internal")) {
  2824. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2825. }
  2826. return new Response(JSON.stringify({ code: 0 }));
  2827. });
  2828. vi.stubGlobal("fetch", fetchMock);
  2829. const provider = createFeishuBotProvider({
  2830. loadCredential: vi.fn(async () => "app-secret-value"),
  2831. });
  2832. await provider.send(createFeishuBot(), {
  2833. botId: "feishu-1",
  2834. provider: "feishu",
  2835. providerUserId: "ou_user",
  2836. text: "Question",
  2837. elicitation: {
  2838. requestId: "ask-select",
  2839. taskId: "task-1",
  2840. runId: "run-1",
  2841. currentQuestionIndex: 0,
  2842. questions: [
  2843. {
  2844. question: "你想在哪里运行贪吃蛇游戏?",
  2845. options: [{ value: "web", label: "网页版 (HTML/CSS/JS)" }],
  2846. },
  2847. ],
  2848. answers: {},
  2849. status: "pending",
  2850. },
  2851. selection: {
  2852. id: "elicitation-ask-select-0",
  2853. token: "abc123def456",
  2854. title: "Question",
  2855. action: "elicitation.respond",
  2856. options: [{ id: "web", label: "网页版 (HTML/CSS/JS)" }],
  2857. },
  2858. });
  2859. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2860. String(url).includes("/open-apis/im/v1/messages"),
  2861. );
  2862. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  2863. const cardJson = JSON.stringify(parseFeishuCardContent(body.content));
  2864. expect(cardJson).toContain("○ 网页版 (HTML/CSS/JS)");
  2865. expect(cardJson).toContain("○ 自定义回答");
  2866. expect(cardJson).not.toContain('"tag":"input"');
  2867. expect(cardJson).not.toContain('"tag":"form"');
  2868. expect(cardJson).not.toContain('"tag":"select_static"');
  2869. expect(cardJson).toContain("/elicitation abc123def456 __custom__");
  2870. });
  2871. it("expands custom input after choosing custom AskUserQuestion answer", async () => {
  2872. const fetchMock = vi.fn(async (url: string) => {
  2873. if (url.endsWith("/tenant_access_token/internal")) {
  2874. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2875. }
  2876. return new Response(JSON.stringify({ code: 0 }));
  2877. });
  2878. vi.stubGlobal("fetch", fetchMock);
  2879. const provider = createFeishuBotProvider({
  2880. loadCredential: vi.fn(async () => "app-secret-value"),
  2881. });
  2882. await provider.send(createFeishuBot(), {
  2883. botId: "feishu-1",
  2884. provider: "feishu",
  2885. providerUserId: "ou_user",
  2886. text: "Question",
  2887. elicitation: {
  2888. requestId: "ask-custom",
  2889. taskId: "task-1",
  2890. runId: "run-1",
  2891. currentQuestionIndex: 0,
  2892. questions: [
  2893. {
  2894. question: "你想在哪里运行贪吃蛇游戏?",
  2895. options: [{ value: "web", label: "网页版 (HTML/CSS/JS)" }],
  2896. },
  2897. ],
  2898. answers: {},
  2899. expandedCustomAnswerQuestionIndexes: [0],
  2900. status: "pending",
  2901. },
  2902. selection: {
  2903. id: "elicitation-ask-custom-0",
  2904. token: "abc123def456",
  2905. title: "Question",
  2906. action: "elicitation.respond",
  2907. options: [{ id: "web", label: "网页版 (HTML/CSS/JS)" }],
  2908. },
  2909. });
  2910. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2911. String(url).includes("/open-apis/im/v1/messages"),
  2912. );
  2913. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  2914. const cardJson = JSON.stringify(parseFeishuCardContent(body.content));
  2915. expect(cardJson).toContain("● 自定义回答");
  2916. expect(cardJson).toContain('"tag":"input"');
  2917. expect(cardJson).toContain("请输入自定义回答");
  2918. expect(cardJson).toContain("/elicitation abc123def456 __custom__");
  2919. expect(cardJson).toContain("/elicitation abc123def456 __form__:");
  2920. });
  2921. it("uses the outbound locale for Feishu AskUserQuestion controls", async () => {
  2922. const fetchMock = vi.fn(async (url: string) => {
  2923. if (url.endsWith("/tenant_access_token/internal")) {
  2924. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2925. }
  2926. return new Response(JSON.stringify({ code: 0 }));
  2927. });
  2928. vi.stubGlobal("fetch", fetchMock);
  2929. const provider = createFeishuBotProvider({
  2930. loadCredential: vi.fn(async () => "app-secret-value"),
  2931. });
  2932. await provider.send(createFeishuBot(), {
  2933. botId: "feishu-1",
  2934. provider: "feishu",
  2935. providerUserId: "ou_user",
  2936. text: "Question",
  2937. locale: "en-US",
  2938. elicitation: {
  2939. requestId: "ask-custom-en",
  2940. taskId: "task-1",
  2941. runId: "run-1",
  2942. currentQuestionIndex: 0,
  2943. questions: [
  2944. {
  2945. question: "Where should the game run?",
  2946. options: [{ value: "web", label: "Web" }],
  2947. },
  2948. ],
  2949. answers: {},
  2950. expandedCustomAnswerQuestionIndexes: [0],
  2951. status: "pending",
  2952. },
  2953. selection: {
  2954. id: "elicitation-ask-custom-en-0",
  2955. token: "abc123def456",
  2956. title: "Question",
  2957. action: "elicitation.respond",
  2958. options: [{ id: "web", label: "Web" }],
  2959. },
  2960. });
  2961. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2962. String(url).includes("/open-apis/im/v1/messages"),
  2963. );
  2964. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  2965. const cardJson = JSON.stringify(parseFeishuCardContent(body.content));
  2966. expect(cardJson).toContain("#### Question");
  2967. expect(cardJson).toContain("● Custom answer");
  2968. expect(cardJson).toContain("Enter a custom answer");
  2969. expect(cardJson).toContain("Done");
  2970. expect(cardJson).toContain("Cancel");
  2971. });
  2972. it("omits cancel buttons when selection disallows cancellation", async () => {
  2973. const fetchMock = vi.fn(async (url: string) => {
  2974. if (url.endsWith("/tenant_access_token/internal")) {
  2975. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2976. }
  2977. return new Response(JSON.stringify({ code: 0 }));
  2978. });
  2979. vi.stubGlobal("fetch", fetchMock);
  2980. const provider = createFeishuBotProvider({
  2981. loadCredential: vi.fn(async () => "app-secret-value"),
  2982. });
  2983. await provider.send(createFeishuBot(), {
  2984. botId: "feishu-1",
  2985. provider: "feishu",
  2986. providerUserId: "ou_user",
  2987. text: "Permission",
  2988. selection: {
  2989. id: "permission-1",
  2990. title: "Permission",
  2991. action: "permission.respond",
  2992. showCancel: false,
  2993. options: [{ id: "/approve req-1 allow", label: "Allow" }],
  2994. },
  2995. });
  2996. const sendCall = fetchMock.mock.calls.find(([url]) =>
  2997. String(url).includes("/open-apis/im/v1/messages"),
  2998. );
  2999. const body = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  3000. const card = parseFeishuCardContent(body.content);
  3001. expect(card).toMatchObject({ schema: "2.0" });
  3002. expect(JSON.stringify(card)).toContain("/approve req-1 allow");
  3003. expect(JSON.stringify(card)).not.toContain('"command":"/cancel"');
  3004. });
  3005. it("updates legacy Feishu cards after acknowledging an action", async () => {
  3006. const fetchMock = vi.fn(async (url: string) => {
  3007. if (url.endsWith("/tenant_access_token/internal")) {
  3008. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3009. }
  3010. return new Response(JSON.stringify({ code: 0 }));
  3011. });
  3012. vi.stubGlobal("fetch", fetchMock);
  3013. const provider = createFeishuBotProvider({
  3014. loadCredential: vi.fn(async () => "app-secret-value"),
  3015. });
  3016. await provider.acknowledgeCallback?.(
  3017. createFeishuBot(),
  3018. {
  3019. botId: "feishu-1",
  3020. event: {
  3021. operator: { operator_id: { open_id: "ou_user" } },
  3022. action: { token: "card-token", value: { command: "/workspace 1" } },
  3023. },
  3024. },
  3025. "已进入 /tmp/workspace 的新任务草稿。",
  3026. );
  3027. const updateCall = fetchMock.mock.calls.find(([url]) =>
  3028. String(url).includes("/interactive/v1/card/update"),
  3029. );
  3030. expect(updateCall?.[1]).toEqual(
  3031. expect.objectContaining({
  3032. method: "POST",
  3033. headers: {
  3034. authorization: "Bearer tenant-token",
  3035. "content-type": "application/json",
  3036. },
  3037. }),
  3038. );
  3039. const body = JSON.parse(String(updateCall?.[1]?.body)) as { token?: string; card?: unknown };
  3040. expect(body.token).toBe("card-token");
  3041. expect(body).toMatchObject({ open_ids: ["ou_user"] });
  3042. expect(body.card).toMatchObject({ schema: "2.0" });
  3043. expect(JSON.stringify(body.card)).toContain("已进入 /tmp/workspace 的新任务草稿。");
  3044. expect(JSON.stringify(body.card)).not.toContain('"command"');
  3045. });
  3046. it("updates Feishu selection cards with original text after acknowledging an action", async () => {
  3047. const fetchMock = vi.fn(async (url: string) => {
  3048. if (url.endsWith("/tenant_access_token/internal")) {
  3049. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3050. }
  3051. return new Response(JSON.stringify({ code: 0 }));
  3052. });
  3053. vi.stubGlobal("fetch", fetchMock);
  3054. const provider = createFeishuBotProvider({
  3055. loadCredential: vi.fn(async () => "app-secret-value"),
  3056. });
  3057. await provider.acknowledgeCallback?.(
  3058. createFeishuBot(),
  3059. {
  3060. botId: "feishu-1",
  3061. event: {
  3062. operator: { operator_id: { open_id: "ou_user" } },
  3063. action: {
  3064. token: "card-token",
  3065. value: {
  3066. command: "/workspace /tmp/workspace",
  3067. zcodeCardText: "请选择工作区",
  3068. },
  3069. },
  3070. },
  3071. },
  3072. "已进入 /tmp/workspace 的新任务草稿。",
  3073. );
  3074. const updateCall = fetchMock.mock.calls.find(([url]) =>
  3075. String(url).includes("/interactive/v1/card/update"),
  3076. );
  3077. expect(updateCall).toBeTruthy();
  3078. const body = JSON.parse(String(updateCall?.[1]?.body)) as { card?: unknown };
  3079. expect(body.card).toMatchObject({ schema: "2.0" });
  3080. expect(JSON.stringify(body.card)).toContain("请选择工作区");
  3081. expect(JSON.stringify(body.card)).not.toContain("已进入 /tmp/workspace 的新任务草稿。");
  3082. expect(JSON.stringify(body.card)).not.toContain('"command"');
  3083. });
  3084. it("updates schema 2 Feishu selection cards with context card tokens", async () => {
  3085. const fetchMock = vi.fn(async (url: string) => {
  3086. if (url.endsWith("/tenant_access_token/internal")) {
  3087. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3088. }
  3089. return new Response(JSON.stringify({ code: 0 }));
  3090. });
  3091. vi.stubGlobal("fetch", fetchMock);
  3092. const provider = createFeishuBotProvider({
  3093. loadCredential: vi.fn(async () => "app-secret-value"),
  3094. });
  3095. await provider.acknowledgeCallback?.(
  3096. createFeishuBot(),
  3097. {
  3098. botId: "feishu-1",
  3099. event: {
  3100. operator: { operator_id: { open_id: "ou_user" } },
  3101. action: {
  3102. behaviors: [
  3103. {
  3104. type: "callback",
  3105. value: {
  3106. command: "/workspace /tmp/workspace",
  3107. zcodeCardText: "请选择工作区",
  3108. },
  3109. },
  3110. ],
  3111. },
  3112. context: { card_update_token: "schema-2-card-token" },
  3113. },
  3114. },
  3115. "已进入 /tmp/workspace 的新任务草稿。",
  3116. );
  3117. const updateCall = fetchMock.mock.calls.find(([url]) =>
  3118. String(url).includes("/interactive/v1/card/update"),
  3119. );
  3120. expect(updateCall).toBeTruthy();
  3121. const body = JSON.parse(String(updateCall?.[1]?.body)) as { token?: string; card?: unknown };
  3122. expect(body.token).toBe("schema-2-card-token");
  3123. expect(body).toMatchObject({ open_ids: ["ou_user"] });
  3124. expect(body.card).toMatchObject({ schema: "2.0" });
  3125. expect(JSON.stringify(body.card)).toContain("请选择工作区");
  3126. expect(JSON.stringify(body.card)).not.toContain('"command"');
  3127. });
  3128. it("updates the same AskUserQuestion card to the next question", async () => {
  3129. const fetchMock = vi.fn(async (url: string) => {
  3130. if (url.endsWith("/tenant_access_token/internal")) {
  3131. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3132. }
  3133. return new Response(JSON.stringify({ code: 0 }));
  3134. });
  3135. vi.stubGlobal("fetch", fetchMock);
  3136. const provider = createFeishuBotProvider({
  3137. loadCredential: vi.fn(async () => "app-secret-value"),
  3138. });
  3139. const result = await provider.acknowledgeCallback?.(
  3140. createFeishuBot(),
  3141. {
  3142. botId: "feishu-1",
  3143. event: {
  3144. operator: { operator_id: { open_id: "ou_user" } },
  3145. action: {
  3146. behaviors: [
  3147. {
  3148. type: "callback",
  3149. value: {
  3150. command: "/elicitation question0token web",
  3151. zcodeCardText: "第一题",
  3152. },
  3153. },
  3154. ],
  3155. },
  3156. context: { card_update_token: "ask-card-token" },
  3157. },
  3158. },
  3159. "第二题",
  3160. {
  3161. botId: "feishu-1",
  3162. provider: "feishu",
  3163. providerUserId: "ou_user",
  3164. text: "第二题",
  3165. selection: {
  3166. id: "elicitation-ask-1-1",
  3167. token: "question1token",
  3168. title: "第二题",
  3169. action: "elicitation.respond",
  3170. options: [{ id: "base", label: "基础玩法" }],
  3171. },
  3172. elicitation: {
  3173. requestId: "ask-1",
  3174. taskId: "task-1",
  3175. currentQuestionIndex: 1,
  3176. questions: [
  3177. { question: "第一题", options: [{ value: "web", label: "网页" }] },
  3178. { question: "第二题", options: [{ value: "base", label: "基础玩法" }] },
  3179. ],
  3180. answers: { "0": ["web"] },
  3181. status: "pending",
  3182. },
  3183. },
  3184. );
  3185. expect(result).toEqual({ handled: true });
  3186. const updateCall = fetchMock.mock.calls.find(([url]) =>
  3187. String(url).includes("/interactive/v1/card/update"),
  3188. );
  3189. const body = JSON.parse(String(updateCall?.[1]?.body)) as { card?: unknown };
  3190. const cardJson = JSON.stringify(body.card);
  3191. expect(cardJson).toContain("第一题");
  3192. expect(cardJson).toContain("第二题");
  3193. expect(cardJson).toContain('"command"');
  3194. });
  3195. it("updates completed AskUserQuestion cards in place and marks the callback handled", async () => {
  3196. const fetchMock = vi.fn(async (url: string) => {
  3197. if (url.endsWith("/tenant_access_token/internal")) {
  3198. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3199. }
  3200. return new Response(JSON.stringify({ code: 0 }));
  3201. });
  3202. vi.stubGlobal("fetch", fetchMock);
  3203. const provider = createFeishuBotProvider({
  3204. loadCredential: vi.fn(async () => "app-secret-value"),
  3205. });
  3206. const result = await provider.acknowledgeCallback?.(
  3207. createFeishuBot(),
  3208. {
  3209. botId: "feishu-1",
  3210. event: {
  3211. operator: { operator_id: { open_id: "ou_user" } },
  3212. action: {
  3213. behaviors: [
  3214. {
  3215. type: "callback",
  3216. value: {
  3217. command: "/elicitation abc123def456 __submit__",
  3218. zcodeCardText: "Question",
  3219. },
  3220. },
  3221. ],
  3222. },
  3223. context: { card_update_token: "ask-card-token" },
  3224. },
  3225. },
  3226. "已提交问答响应。",
  3227. {
  3228. botId: "feishu-1",
  3229. provider: "feishu",
  3230. providerUserId: "ou_user",
  3231. text: "已提交问答响应。",
  3232. elicitation: {
  3233. requestId: "ask-1",
  3234. taskId: "task-1",
  3235. runId: "run-1",
  3236. currentQuestionIndex: 1,
  3237. questions: [
  3238. {
  3239. question: "你想在哪里运行贪吃蛇游戏?",
  3240. options: [{ value: "web", label: "网页版 (HTML/CSS/JS)" }],
  3241. },
  3242. {
  3243. question: "你希望游戏有什么功能?",
  3244. options: [
  3245. { value: "base", label: "基础玩法" },
  3246. { value: "score", label: "分数系统" },
  3247. ],
  3248. multiSelect: true,
  3249. },
  3250. ],
  3251. answers: { "0": ["web"], "1": ["base", "score"] },
  3252. status: "completed",
  3253. },
  3254. },
  3255. );
  3256. expect(result).toEqual({ handled: true });
  3257. const updateCall = fetchMock.mock.calls.find(([url]) =>
  3258. String(url).includes("/interactive/v1/card/update"),
  3259. );
  3260. const body = JSON.parse(String(updateCall?.[1]?.body)) as { token?: string; card?: unknown };
  3261. const cardJson = JSON.stringify(body.card);
  3262. expect(body.token).toBe("ask-card-token");
  3263. expect(body).toMatchObject({ open_ids: ["ou_user"] });
  3264. expect(body.card).toMatchObject({ schema: "2.0" });
  3265. expect(cardJson).toContain("#### 1/2 你想在哪里运行贪吃蛇游戏?");
  3266. expect(cardJson).toContain("网页版 (HTML/CSS/JS)");
  3267. expect(cardJson).toContain("#### 2/2 你希望游戏有什么功能?");
  3268. expect(cardJson).toContain("基础玩法, 分数系统");
  3269. expect(cardJson).not.toContain('"content":"---\\n"');
  3270. expect(cardJson).not.toContain("✅ Questions answered");
  3271. expect(cardJson).not.toContain('"command"');
  3272. });
  3273. it("uses Feishu Typing reactions as provider typing state", async () => {
  3274. const fetchMock = vi.fn(async (url: string) => {
  3275. if (url.endsWith("/tenant_access_token/internal")) {
  3276. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3277. }
  3278. if (url.endsWith("/messages/om_message/reactions")) {
  3279. return new Response(JSON.stringify({ code: 0, data: { reaction_id: "reaction-1" } }));
  3280. }
  3281. return new Response(JSON.stringify({ code: 0 }));
  3282. });
  3283. vi.stubGlobal("fetch", fetchMock);
  3284. const provider = createFeishuBotProvider({
  3285. loadCredential: vi.fn(async () => "app-secret-value"),
  3286. });
  3287. await provider.startTyping?.(createFeishuBot(), {
  3288. providerUserId: "ou_user",
  3289. providerMessageId: "om_message",
  3290. });
  3291. await provider.stopTyping?.(createFeishuBot(), {
  3292. providerUserId: "ou_user",
  3293. providerMessageId: "om_message",
  3294. });
  3295. const addCall = fetchMock.mock.calls.find(([url]) =>
  3296. String(url).endsWith("/messages/om_message/reactions"),
  3297. );
  3298. expect(addCall?.[1]).toEqual(
  3299. expect.objectContaining({
  3300. method: "POST",
  3301. headers: {
  3302. authorization: "Bearer tenant-token",
  3303. "content-type": "application/json",
  3304. },
  3305. body: JSON.stringify({
  3306. reaction_type: {
  3307. emoji_type: "Typing",
  3308. },
  3309. }),
  3310. }),
  3311. );
  3312. expect(fetchMock).toHaveBeenCalledWith(
  3313. "https://open.feishu.cn/open-apis/im/v1/messages/om_message/reactions/reaction-1",
  3314. expect.objectContaining({
  3315. method: "DELETE",
  3316. headers: {
  3317. authorization: "Bearer tenant-token",
  3318. },
  3319. }),
  3320. );
  3321. });
  3322. it("keeps command typing reactions until explicit stop", async () => {
  3323. const fetchMock = vi.fn(async (url: string) => {
  3324. if (url.endsWith("/tenant_access_token/internal")) {
  3325. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3326. }
  3327. if (url.endsWith("/messages/om_command/reactions")) {
  3328. return new Response(JSON.stringify({ code: 0, data: { reaction_id: "reaction-command" } }));
  3329. }
  3330. return new Response(JSON.stringify({ code: 0 }));
  3331. });
  3332. vi.stubGlobal("fetch", fetchMock);
  3333. const provider = createFeishuBotProvider({
  3334. loadCredential: vi.fn(async () => "app-secret-value"),
  3335. });
  3336. await provider.sendTyping?.(createFeishuBot(), {
  3337. providerUserId: "ou_user",
  3338. providerMessageId: "om_command",
  3339. });
  3340. expect(
  3341. fetchMock.mock.calls.some(
  3342. ([url, init]) =>
  3343. String(url).endsWith("/messages/om_command/reactions/reaction-command") &&
  3344. (init as RequestInit | undefined)?.method === "DELETE",
  3345. ),
  3346. ).toBe(false);
  3347. await provider.stopTyping?.(createFeishuBot(), {
  3348. providerUserId: "ou_user",
  3349. providerMessageId: "om_command",
  3350. });
  3351. expect(fetchMock).toHaveBeenCalledWith(
  3352. "https://open.feishu.cn/open-apis/im/v1/messages/om_command/reactions/reaction-command",
  3353. expect.objectContaining({ method: "DELETE" }),
  3354. );
  3355. });
  3356. it("lets long-running Feishu typing take over transient command typing", async () => {
  3357. const fetchMock = vi.fn(async (url: string) => {
  3358. if (url.endsWith("/tenant_access_token/internal")) {
  3359. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3360. }
  3361. if (url.endsWith("/messages/om_takeover/reactions")) {
  3362. return new Response(
  3363. JSON.stringify({ code: 0, data: { reaction_id: "reaction-takeover" } }),
  3364. );
  3365. }
  3366. return new Response(JSON.stringify({ code: 0 }));
  3367. });
  3368. vi.stubGlobal("fetch", fetchMock);
  3369. const provider = createFeishuBotProvider({
  3370. loadCredential: vi.fn(async () => "app-secret-value"),
  3371. });
  3372. const bot = createFeishuBot();
  3373. const target = {
  3374. providerUserId: "ou_user",
  3375. providerMessageId: "om_takeover",
  3376. };
  3377. await provider.sendTyping?.(bot, target);
  3378. await provider.startTyping?.(bot, target);
  3379. expect(
  3380. fetchMock.mock.calls.some(
  3381. ([url, init]) =>
  3382. String(url).endsWith("/messages/om_takeover/reactions/reaction-takeover") &&
  3383. (init as RequestInit | undefined)?.method === "DELETE",
  3384. ),
  3385. ).toBe(false);
  3386. await provider.stopTyping?.(bot, target);
  3387. expect(fetchMock).toHaveBeenCalledWith(
  3388. "https://open.feishu.cn/open-apis/im/v1/messages/om_takeover/reactions/reaction-takeover",
  3389. expect.objectContaining({ method: "DELETE" }),
  3390. );
  3391. });
  3392. });