botsFeishuProvider.test.ts 125 KB

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