botsService.messageFlow.test.ts 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487
  1. import { Buffer } from "node:buffer";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { encodeCustomModelValue, type BotsStateFile, type ZCodeStreamEvent } from "@zcode/shared";
  4. import * as f from "./botsService.fixtures.js";
  5. const actor = {
  6. provider: "webhook" as const,
  7. botId: "webhook-1",
  8. providerUserId: "user-1",
  9. chatType: "private" as const,
  10. };
  11. const feishuActor = {
  12. provider: "feishu" as const,
  13. botId: "feishu-1",
  14. providerUserId: "ou_user",
  15. chatType: "private" as const,
  16. };
  17. const weixinActor = {
  18. provider: "weixin" as const,
  19. botId: "weixin-1",
  20. providerUserId: "wx_user",
  21. chatType: "private" as const,
  22. };
  23. async function bind(service: ReturnType<typeof f.createBotsService>) {
  24. const code = await service.createBindCode({ botId: "webhook-1" });
  25. await service.handleInboundMessage({
  26. botId: "webhook-1",
  27. text: `/bind ${code.code}`,
  28. actor,
  29. });
  30. }
  31. function createDeferred<T>() {
  32. let resolve!: (value: T) => void;
  33. let reject!: (reason?: unknown) => void;
  34. const promise = new Promise<T>((promiseResolve, promiseReject) => {
  35. resolve = promiseResolve;
  36. reject = promiseReject;
  37. });
  38. return { promise, resolve, reject };
  39. }
  40. describe("botsService messageFlow", () => {
  41. it.each(["available", "unavailable", "missing"] as const)(
  42. "绑定后从 Session 原选择解析下一条输入,不读 Bot 默认或创建草稿:%s",
  43. async (availability) => {
  44. const original = {
  45. providerId: "account:personal",
  46. modelId: "glm",
  47. options: { reasoningLevel: "high" },
  48. };
  49. const effective = { ...original, providerId: "account:team" };
  50. const repo = f.createMemoryRepo(f.baseConfig);
  51. const tasks = f.createLegacyTaskService();
  52. const getView = vi.fn(async () => ({
  53. providers: [],
  54. effectiveSelection: availability === "available" ? effective : null,
  55. preferredSelection: effective,
  56. }));
  57. const service = f.createBotsService({
  58. repo: repo as never,
  59. legacyTaskService: tasks,
  60. modelSelectionService: { getView } as never,
  61. });
  62. await bind(service);
  63. const bound = await repo.readState();
  64. bound.bots[actor.botId] = {
  65. botId: actor.botId,
  66. workspacePath: "/tmp/workspace",
  67. workspaceIdentity: "ssh://host/tmp/workspace",
  68. updatedAt: Date.now(),
  69. mode: "task",
  70. activeTaskId: "task-1",
  71. draftOptions: undefined,
  72. };
  73. await repo.writeState(bound);
  74. vi.mocked(tasks.getTaskModelSelection).mockResolvedValue(
  75. availability === "missing" ? null : original,
  76. );
  77. vi.mocked(tasks.sendPrompt).mockClear();
  78. getView.mockClear();
  79. const submission = service.handleInboundMessage({ botId: actor.botId, actor, text: "next" });
  80. if (availability === "available") {
  81. await submission;
  82. await vi.waitFor(() =>
  83. expect(tasks.sendPrompt).toHaveBeenCalledWith(
  84. expect.objectContaining({
  85. taskId: "task-1",
  86. content: "next",
  87. modelSelection: effective,
  88. }),
  89. ),
  90. );
  91. } else {
  92. await expect(submission).rejects.toThrow("原选择已保留");
  93. expect(tasks.sendPrompt).not.toHaveBeenCalled();
  94. expect(tasks.setModel).not.toHaveBeenCalled();
  95. }
  96. expect(tasks.getTaskModelSelection).toHaveBeenCalledWith({ taskId: "task-1" });
  97. if (availability === "missing") expect(getView).not.toHaveBeenCalled();
  98. else expect(getView).toHaveBeenCalledWith(expect.objectContaining({ selection: original }));
  99. const state = await repo.readState();
  100. expect(state.bots[actor.botId]?.draftOptions).toBeUndefined();
  101. expect(original.providerId).toBe("account:personal");
  102. service.disposeAll();
  103. },
  104. );
  105. it("startup reads current storage without re-running legacy migration or writing state", async () => {
  106. const baseRepo = f.createMemoryRepo(f.feishuConfig);
  107. const readState = vi.fn(() => baseRepo.readState());
  108. const writeState = vi.fn((state: BotsStateFile) => baseRepo.writeState(state));
  109. const service = f.createBotsService({ repo: { ...baseRepo, readState, writeState } as never });
  110. await vi.waitFor(() => expect(readState).toHaveBeenCalled());
  111. expect(writeState).not.toHaveBeenCalled();
  112. service.disposeAll();
  113. });
  114. it("activates Weixin on the first message after QR confirmation", async () => {
  115. const repo = f.createMemoryRepo(f.weixinConfig, {
  116. version: 3,
  117. bots: {
  118. "weixin-1": {
  119. botId: "weixin-1",
  120. workspacePath: "/tmp/workspace",
  121. workspaceIdentity: "ssh://host/tmp/workspace",
  122. workspaceId: "ssh://host/tmp/workspace",
  123. mode: "draft",
  124. activeTaskId: null,
  125. weixinGetUpdatesBuf: "cursor-only",
  126. updatedAt: Date.now(),
  127. },
  128. },
  129. });
  130. const legacyTaskService = f.createLegacyTaskService();
  131. const service = f.createBotsService({
  132. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  133. legacyTaskService,
  134. repo: repo as never,
  135. });
  136. const activationReplies = await service.handleInboundMessage({
  137. botId: "weixin-1",
  138. text: "你好",
  139. actor: {
  140. provider: "weixin",
  141. botId: "weixin-1",
  142. providerUserId: "wx_user",
  143. chatType: "private",
  144. },
  145. });
  146. expect(activationReplies[0]?.text).toContain("微信 Bot 已激活");
  147. expect(legacyTaskService.createTask).not.toHaveBeenCalled();
  148. const replies = await service.handleInboundMessage({
  149. botId: "weixin-1",
  150. text: "请检查当前项目",
  151. actor: {
  152. provider: "weixin",
  153. botId: "weixin-1",
  154. providerUserId: "wx_user",
  155. chatType: "private",
  156. },
  157. });
  158. expect(replies).toEqual([]);
  159. expect(legacyTaskService.createTask).toHaveBeenCalledWith(
  160. expect.objectContaining({
  161. workspacePath: "/tmp/workspace",
  162. workspaceIdentity: "ssh://host/tmp/workspace",
  163. provider: "glm",
  164. }),
  165. );
  166. service.disposeAll();
  167. });
  168. it("renders Weixin selections as plain numbered text without native selection payload", async () => {
  169. const repo = f.createMemoryRepo(f.weixinConfig);
  170. const service = f.createBotsService({
  171. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  172. legacyTaskService: f.createLegacyTaskService(),
  173. repo: repo as never,
  174. });
  175. const replies = await service.handleInboundMessage({
  176. botId: "weixin-1",
  177. text: "/workspace",
  178. actor: {
  179. provider: "weixin",
  180. botId: "weixin-1",
  181. providerUserId: "wx_user",
  182. chatType: "private",
  183. },
  184. });
  185. expect(replies[0]).toMatchObject({
  186. provider: "weixin",
  187. providerUserId: "wx_user",
  188. });
  189. expect(replies[0]).not.toHaveProperty("selection");
  190. expect(replies[0]?.text).toContain("选择 workspace");
  191. expect(replies[0]?.text).toContain("1.");
  192. expect(replies[0]?.text).toContain("[远端]");
  193. expect(replies[0]?.text).not.toContain("[本地]");
  194. expect(replies[0]?.text).toContain("0. 取消");
  195. expect(replies[0]?.text).toContain("回复数字选择,0 取消。");
  196. expect(replies[0]?.text).not.toContain("/workspace");
  197. expect(replies[0]?.text).not.toContain("ssh://host/tmp/workspace");
  198. service.disposeAll();
  199. });
  200. it("marks remote workspaces in native selection labels", async () => {
  201. const repo = f.createMemoryRepo(f.baseConfig);
  202. const service = f.createBotsService({
  203. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  204. legacyTaskService: f.createLegacyTaskService(),
  205. repo: repo as never,
  206. });
  207. await bind(service);
  208. const replies = await service.handleInboundMessage({
  209. botId: "webhook-1",
  210. text: "/workspace",
  211. actor,
  212. });
  213. expect(replies[0]?.selection?.options[0]?.label).toContain("[远端]");
  214. expect(replies[0]?.selection?.options[0]).not.toHaveProperty("description");
  215. service.disposeAll();
  216. });
  217. it("localizes Weixin text selection cancel hints", async () => {
  218. const repo = f.createMemoryRepo(f.weixinConfig);
  219. const service = f.createBotsService({
  220. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  221. legacyTaskService: f.createLegacyTaskService(),
  222. settingService: f.createSettingService({
  223. locale: "en-US",
  224. lastWorkspaceSession: [
  225. {
  226. kind: "remote",
  227. workspacePath: "/tmp/workspace",
  228. workspaceIdentity: "ssh://host/tmp/workspace",
  229. },
  230. ],
  231. }),
  232. repo: repo as never,
  233. });
  234. const replies = await service.handleInboundMessage({
  235. botId: "weixin-1",
  236. text: "/workspace",
  237. actor: weixinActor,
  238. });
  239. expect(replies[0]?.text).toContain("0. Cancel");
  240. expect(replies[0]?.text).toContain("Reply with a number to choose, or 0 to cancel.");
  241. service.disposeAll();
  242. });
  243. it("cancels a Weixin text selection with 0", async () => {
  244. const repo = f.createMemoryRepo(f.weixinConfig);
  245. const service = f.createBotsService({
  246. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  247. legacyTaskService: f.createLegacyTaskService(),
  248. repo: repo as never,
  249. });
  250. await service.handleInboundMessage({
  251. botId: "weixin-1",
  252. text: "/workspace",
  253. actor: weixinActor,
  254. });
  255. const replies = await service.handleInboundMessage({
  256. botId: "weixin-1",
  257. text: "0",
  258. actor: weixinActor,
  259. });
  260. expect(replies[0]?.text).toContain("工作区:");
  261. expect(replies[0]?.text).not.toContain("Provider:");
  262. service.disposeAll();
  263. });
  264. it("resolves Weixin workspace/reply selections and allows draft model selection", async () => {
  265. const repo = f.createMemoryRepo(f.weixinConfig);
  266. const legacyTaskService = f.createLegacyTaskService();
  267. const service = f.createBotsService({
  268. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  269. legacyTaskService,
  270. modelSelectionService: f.createModelSelectionService([
  271. {
  272. id: "runtime-provider",
  273. name: "Runtime Provider",
  274. endpoints: { baseURL: "https://example.com/v1", paths: { "openai-compatible": "" } },
  275. defaultKind: "openai-compatible",
  276. apiKey: "key",
  277. models: [
  278. "gpt-5.3",
  279. {
  280. id: "gpt-5.4",
  281. config: {
  282. optionSpecs: {
  283. reasoningLevel: {
  284. values: ["low", "medium", "high"],
  285. },
  286. },
  287. },
  288. },
  289. ],
  290. createdAt: 1,
  291. updatedAt: 1,
  292. },
  293. ]),
  294. repo: repo as never,
  295. });
  296. await service.handleInboundMessage({
  297. botId: "weixin-1",
  298. text: "/workspace",
  299. actor: weixinActor,
  300. });
  301. const workspaceReplies = await service.handleInboundMessage({
  302. botId: "weixin-1",
  303. text: "1",
  304. actor: weixinActor,
  305. });
  306. expect(workspaceReplies[0]?.text).toContain("工作区:");
  307. expect(workspaceReplies[0]?.text).toContain("任务: 草稿");
  308. const modelReplies = await service.handleInboundMessage({
  309. botId: "weixin-1",
  310. text: "/model",
  311. actor: weixinActor,
  312. });
  313. expect(modelReplies[0]?.text).toContain("选择模型供应商");
  314. const replyList = await service.handleInboundMessage({
  315. botId: "weixin-1",
  316. text: "/reply",
  317. actor: weixinActor,
  318. });
  319. expect(replyList[0]?.text).toContain("标准回复");
  320. expect(replyList[0]?.text).toContain("完整回复");
  321. expect(replyList[0]?.text).toContain("摘要回复");
  322. expect(replyList[0]?.text).not.toContain("流式卡片");
  323. const rejectedStreamingCard = await service.handleInboundMessage({
  324. botId: "weixin-1",
  325. text: "/reply streaming_card",
  326. actor: weixinActor,
  327. });
  328. expect(rejectedStreamingCard[0]?.text).toContain("未找到回复颗粒度");
  329. await service.handleInboundMessage({
  330. botId: "weixin-1",
  331. text: "/reply",
  332. actor: weixinActor,
  333. });
  334. const replyReplies = await service.handleInboundMessage({
  335. botId: "weixin-1",
  336. text: "2",
  337. actor: weixinActor,
  338. });
  339. expect(replyReplies[0]?.text).toContain("工作区:");
  340. expect(replyReplies[0]?.text).toContain("任务: 草稿");
  341. expect((await repo.readConfig()).bots[0]).toMatchObject({
  342. currentOptions: {},
  343. replyMode: "assistant_toolcalls_changes",
  344. });
  345. service.disposeAll();
  346. });
  347. it("limits Feishu reply granularity command to streaming cards", async () => {
  348. const repo = f.createMemoryRepo({
  349. ...f.feishuConfig,
  350. bots: [
  351. {
  352. ...f.feishuConfig.bots[0]!,
  353. replyMode: "assistant_changes",
  354. },
  355. ],
  356. });
  357. const service = f.createBotsService({
  358. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  359. legacyTaskService: f.createLegacyTaskService(),
  360. repo: repo as never,
  361. });
  362. const listReplies = await service.handleInboundMessage({
  363. botId: "feishu-1",
  364. text: "/reply",
  365. actor: feishuActor,
  366. });
  367. expect(listReplies[0]?.selection?.options).toEqual([
  368. expect.objectContaining({
  369. id: "streaming_card",
  370. label: expect.stringContaining("流式卡片"),
  371. }),
  372. ]);
  373. expect(listReplies[0]?.selection?.currentId).toBe("streaming_card");
  374. const rejectedReplies = await service.handleInboundMessage({
  375. botId: "feishu-1",
  376. text: "/reply assistant_changes",
  377. actor: feishuActor,
  378. });
  379. expect(rejectedReplies[0]?.text).toContain("未找到回复颗粒度");
  380. expect((await repo.readConfig()).bots[0]?.replyMode).toBe("assistant_changes");
  381. const acceptedReplies = await service.handleInboundMessage({
  382. botId: "feishu-1",
  383. text: "/reply 1",
  384. actor: feishuActor,
  385. });
  386. expect(acceptedReplies[0]?.text).toContain("工作区:");
  387. expect((await repo.readConfig()).bots[0]?.replyMode).toBe("streaming_card");
  388. service.disposeAll();
  389. });
  390. it("keeps the current remote workspace available in /workspace selections", async () => {
  391. const repo = f.createMemoryRepo(f.weixinConfig, {
  392. version: 3,
  393. bots: {
  394. "weixin-1": {
  395. botId: "weixin-1",
  396. workspacePath: "/tmp/workspace",
  397. workspaceIdentity: "ssh://host/tmp/workspace",
  398. workspaceId: "ssh://host/tmp/workspace",
  399. mode: "task",
  400. activeTaskId: "task-1",
  401. updatedAt: Date.now(),
  402. },
  403. },
  404. });
  405. const service = f.createBotsService({
  406. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  407. legacyTaskService: f.createLegacyTaskService(),
  408. settingService: f.createSettingService({
  409. locale: "zh-CN",
  410. lastWorkspaceSession: [
  411. {
  412. kind: "local",
  413. workspacePath: "/tmp/workspace",
  414. },
  415. ],
  416. }),
  417. repo: repo as never,
  418. });
  419. const listReplies = await service.handleInboundMessage({
  420. botId: "weixin-1",
  421. text: "/workspace",
  422. actor: weixinActor,
  423. });
  424. expect(listReplies[0]?.text).toContain("[远端]");
  425. const switchReplies = await service.handleInboundMessage({
  426. botId: "weixin-1",
  427. text: "1",
  428. actor: weixinActor,
  429. });
  430. expect(switchReplies[0]?.text).toContain("工作区:");
  431. expect(switchReplies[0]?.text).toContain("任务: 草稿");
  432. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  433. workspacePath: "/tmp/workspace",
  434. workspaceIdentity: "ssh://host/tmp/workspace",
  435. workspaceId: "ssh://host/tmp/workspace",
  436. activeTaskId: null,
  437. mode: "draft",
  438. });
  439. service.disposeAll();
  440. });
  441. it("resolves Weixin plain-number pending selections for config and task", async () => {
  442. const repo = f.createMemoryRepo(f.weixinConfig, {
  443. version: 3,
  444. bots: {
  445. "weixin-1": {
  446. botId: "weixin-1",
  447. workspacePath: "/tmp/workspace",
  448. workspaceIdentity: "ssh://host/tmp/workspace",
  449. workspaceId: "ssh://host/tmp/workspace",
  450. mode: "task",
  451. activeTaskId: "task-1",
  452. updatedAt: Date.now(),
  453. },
  454. },
  455. });
  456. const legacyTaskService = f.createLegacyTaskService();
  457. const configOptions = [
  458. {
  459. id: "reasoning_effort",
  460. category: "thought_level",
  461. type: "select" as const,
  462. currentValue: "low",
  463. options: [{ value: "medium", name: "Medium" }],
  464. },
  465. {
  466. id: "runtime_mode",
  467. category: "mode",
  468. type: "select" as const,
  469. currentValue: "default",
  470. options: [{ value: "auto", name: "Auto" }],
  471. },
  472. ];
  473. Object.assign(legacyTaskService, {
  474. getTaskConfigOptions: vi.fn(async () => configOptions),
  475. listTasks: vi.fn(async () => [
  476. {
  477. taskId: "task-1",
  478. title: "First task",
  479. status: "completed",
  480. workspacePath: "/tmp/workspace",
  481. workspaceIdentity: "ssh://host/tmp/workspace",
  482. provider: "codex",
  483. },
  484. {
  485. taskId: "task-2",
  486. title: "Second task",
  487. status: "completed",
  488. workspacePath: "/tmp/workspace",
  489. workspaceIdentity: "ssh://host/tmp/workspace",
  490. provider: "codex",
  491. },
  492. ]),
  493. });
  494. const service = f.createBotsService({
  495. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  496. legacyTaskService,
  497. repo: repo as never,
  498. });
  499. await service.handleInboundMessage({
  500. botId: "weixin-1",
  501. text: "/think",
  502. actor: weixinActor,
  503. });
  504. const thoughtReplies = await service.handleInboundMessage({
  505. botId: "weixin-1",
  506. text: "1",
  507. actor: weixinActor,
  508. });
  509. expect(thoughtReplies[0]?.text).toContain("工作区:");
  510. expect(thoughtReplies[0]?.text).toContain("任务:");
  511. const modeReplies = await service.handleInboundMessage({
  512. botId: "weixin-1",
  513. text: "/mode",
  514. actor: weixinActor,
  515. });
  516. expect(modeReplies[0]?.text).toContain("yolo");
  517. await service.handleInboundMessage({
  518. botId: "weixin-1",
  519. text: "/task",
  520. actor: weixinActor,
  521. });
  522. expect(
  523. (
  524. await service.handleInboundMessage({
  525. botId: "weixin-1",
  526. text: "2",
  527. actor: weixinActor,
  528. })
  529. )[0]?.text,
  530. ).toContain("工作区:");
  531. expect((await repo.readConfig()).bots[0]?.currentOptions).toEqual({});
  532. expect(legacyTaskService.setConfigOption).toHaveBeenCalledWith(
  533. expect.objectContaining({
  534. taskId: "task-1",
  535. configId: "reasoning_effort",
  536. value: "medium",
  537. }),
  538. );
  539. expect(legacyTaskService.setConfigOption).not.toHaveBeenCalledWith(
  540. expect.objectContaining({ configId: "mode" }),
  541. );
  542. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  543. activeTaskId: "task-2",
  544. mode: "task",
  545. });
  546. service.disposeAll();
  547. });
  548. it("switches remote task from the displayed /task selection when later listTasks misses it", async () => {
  549. const repo = f.createMemoryRepo(f.weixinConfig, {
  550. version: 3,
  551. bots: {
  552. "weixin-1": {
  553. botId: "weixin-1",
  554. workspacePath: "/tmp/workspace",
  555. workspaceIdentity: "ssh://host/tmp/workspace",
  556. workspaceId: "ssh://host/tmp/workspace",
  557. mode: "task",
  558. activeTaskId: "task-1",
  559. updatedAt: Date.now(),
  560. },
  561. },
  562. });
  563. const legacyTaskService = f.createLegacyTaskService();
  564. vi.mocked(legacyTaskService.listTasks)
  565. .mockResolvedValueOnce([
  566. {
  567. taskId: "task-1",
  568. title: "Remote first task",
  569. status: "completed",
  570. workspacePath: "/tmp/workspace",
  571. workspaceIdentity: "ssh://host/tmp/workspace",
  572. provider: "codex",
  573. },
  574. {
  575. taskId: "task-2",
  576. title: "Remote second task",
  577. status: "completed",
  578. workspacePath: "/tmp/workspace",
  579. workspaceIdentity: "ssh://host/tmp/workspace",
  580. provider: "codex",
  581. },
  582. ])
  583. .mockResolvedValue([]);
  584. const service = f.createBotsService({
  585. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  586. legacyTaskService,
  587. repo: repo as never,
  588. });
  589. const taskReplies = await service.handleInboundMessage({
  590. botId: "weixin-1",
  591. text: "/task",
  592. actor: weixinActor,
  593. });
  594. expect(taskReplies[0]?.text).toContain("Remote second task");
  595. const switchReplies = await service.handleInboundMessage({
  596. botId: "weixin-1",
  597. text: "2",
  598. actor: weixinActor,
  599. });
  600. expect(switchReplies[0]?.text).toContain("工作区:");
  601. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  602. activeTaskId: "task-2",
  603. mode: "task",
  604. workspaceIdentity: "ssh://host/tmp/workspace",
  605. });
  606. service.disposeAll();
  607. });
  608. it("treats non-number text after a Weixin /task menu as a normal prompt", async () => {
  609. const repo = f.createMemoryRepo(f.weixinConfig, {
  610. version: 3,
  611. bots: {
  612. "weixin-1": {
  613. botId: "weixin-1",
  614. workspacePath: "/tmp/workspace",
  615. workspaceIdentity: "ssh://host/tmp/workspace",
  616. workspaceId: "ssh://host/tmp/workspace",
  617. mode: "task",
  618. activeTaskId: "task-1",
  619. updatedAt: Date.now(),
  620. },
  621. },
  622. });
  623. const legacyTaskService = f.createLegacyTaskService();
  624. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  625. {
  626. taskId: "task-1",
  627. title: "Current task",
  628. status: "completed",
  629. workspacePath: "/tmp/workspace",
  630. workspaceIdentity: "ssh://host/tmp/workspace",
  631. provider: "codex",
  632. },
  633. {
  634. taskId: "task-2",
  635. title: "hello",
  636. status: "completed",
  637. workspacePath: "/tmp/workspace",
  638. workspaceIdentity: "ssh://host/tmp/workspace",
  639. provider: "codex",
  640. },
  641. ]);
  642. const service = f.createBotsService({
  643. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  644. legacyTaskService,
  645. repo: repo as never,
  646. });
  647. const taskReplies = await service.handleInboundMessage({
  648. botId: "weixin-1",
  649. text: "/task",
  650. actor: weixinActor,
  651. });
  652. expect(taskReplies[0]?.text).toContain("hello");
  653. const promptReplies = await service.handleInboundMessage({
  654. botId: "weixin-1",
  655. text: "hello",
  656. actor: weixinActor,
  657. });
  658. expect(promptReplies).toEqual([]);
  659. expect(legacyTaskService.resumeTask).toHaveBeenCalledWith(
  660. expect.objectContaining({ taskId: "task-1" }),
  661. );
  662. expect(legacyTaskService.sendPrompt).toHaveBeenCalledWith(
  663. expect.objectContaining({ taskId: "task-1", content: "hello" }),
  664. );
  665. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  666. activeTaskId: "task-1",
  667. });
  668. service.disposeAll();
  669. });
  670. it("does not allow implicit pending selection replies outside Weixin", async () => {
  671. const telegramActor = {
  672. provider: "telegram" as const,
  673. botId: "telegram-1",
  674. providerUserId: "user-1",
  675. chatType: "private" as const,
  676. };
  677. const repo = f.createMemoryRepo(f.telegramConfig, {
  678. version: 3,
  679. bots: {
  680. "telegram-1": {
  681. botId: "telegram-1",
  682. workspacePath: "/tmp/workspace",
  683. workspaceIdentity: "ssh://host/tmp/workspace",
  684. workspaceId: "ssh://host/tmp/workspace",
  685. mode: "task",
  686. activeTaskId: "task-1",
  687. updatedAt: Date.now(),
  688. },
  689. },
  690. });
  691. const legacyTaskService = f.createLegacyTaskService();
  692. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  693. {
  694. taskId: "task-1",
  695. title: "Current task",
  696. status: "completed",
  697. workspacePath: "/tmp/workspace",
  698. workspaceIdentity: "ssh://host/tmp/workspace",
  699. provider: "codex",
  700. },
  701. {
  702. taskId: "task-2",
  703. title: "Next task",
  704. status: "completed",
  705. workspacePath: "/tmp/workspace",
  706. workspaceIdentity: "ssh://host/tmp/workspace",
  707. provider: "codex",
  708. },
  709. ]);
  710. const service = f.createBotsService({
  711. credentialService: f.createCredentialService({
  712. "telegram-token": "token",
  713. }),
  714. legacyTaskService,
  715. repo: repo as never,
  716. });
  717. const taskReplies = await service.handleInboundMessage({
  718. botId: "telegram-1",
  719. text: "/task",
  720. actor: telegramActor,
  721. });
  722. expect(taskReplies[0]).toHaveProperty("selection");
  723. const promptReplies = await service.handleInboundMessage({
  724. botId: "telegram-1",
  725. text: "2",
  726. actor: telegramActor,
  727. });
  728. expect(promptReplies).toEqual([]);
  729. expect(legacyTaskService.resumeTask).toHaveBeenCalledWith(
  730. expect.objectContaining({ taskId: "task-1" }),
  731. );
  732. expect(legacyTaskService.sendPrompt).toHaveBeenCalledWith(
  733. expect.objectContaining({ taskId: "task-1", content: "2" }),
  734. );
  735. expect((await repo.readState()).bots["telegram-1"]).toMatchObject({
  736. activeTaskId: "task-1",
  737. });
  738. service.disposeAll();
  739. });
  740. it("syncs active task model, mode, and cli changes through ZCode Agent and broadcasts UI updates", async () => {
  741. const repo = f.createMemoryRepo(f.weixinConfig, {
  742. version: 3,
  743. bots: {
  744. "weixin-1": {
  745. botId: "weixin-1",
  746. workspacePath: "/tmp/workspace",
  747. workspaceIdentity: "ssh://host/tmp/workspace",
  748. workspaceId: "ssh://host/tmp/workspace",
  749. mode: "task",
  750. activeTaskId: "task-1",
  751. updatedAt: Date.now(),
  752. },
  753. },
  754. });
  755. const legacyTaskService = f.createLegacyTaskService();
  756. const configOptions = [
  757. {
  758. id: "model",
  759. category: "model",
  760. type: "select" as const,
  761. currentValue: "gpt-5.3",
  762. options: [
  763. {
  764. value: "gpt-5.3",
  765. name: "GPT-5.3",
  766. modelProviderId: "glm",
  767. modelProviderName: "ZCode Agent",
  768. },
  769. {
  770. value: "gpt-5.4",
  771. name: "GPT-5.4",
  772. modelProviderId: "glm",
  773. modelProviderName: "ZCode Agent",
  774. },
  775. ],
  776. },
  777. {
  778. id: "mode",
  779. category: "mode",
  780. type: "select" as const,
  781. currentValue: "default",
  782. options: [{ value: "plan", name: "Plan" }],
  783. },
  784. ];
  785. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue(configOptions);
  786. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  787. {
  788. taskId: "task-1",
  789. title: "Active task",
  790. workspacePath: "/tmp/workspace",
  791. workspaceIdentity: "ssh://host/tmp/workspace",
  792. provider: "codex",
  793. model: "gpt-5.3",
  794. mode: "default",
  795. status: "completed",
  796. },
  797. ]);
  798. vi.mocked(legacyTaskService.setModel).mockResolvedValue([
  799. { ...configOptions[0]!, currentValue: "gpt-5.4" },
  800. configOptions[1]!,
  801. ]);
  802. vi.mocked(legacyTaskService.setConfigOption).mockResolvedValue([
  803. configOptions[0]!,
  804. { ...configOptions[1]!, currentValue: "plan" },
  805. ]);
  806. const broadcastService = f.createBroadcastService();
  807. const zcodeSessionService = f.createZCodeSessionService(
  808. f.createZCodeSessionSettingsFromConfigOptions(configOptions),
  809. );
  810. const service = f.createBotsService({
  811. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  812. legacyTaskService,
  813. zcodeSessionService,
  814. broadcastService,
  815. modelSelectionService: f.createModelSelectionService([
  816. {
  817. id: "custom-provider",
  818. name: "Custom Provider",
  819. endpoints: {
  820. baseURL: "https://example.com/v1",
  821. paths: { "openai-compatible": "" },
  822. },
  823. defaultKind: "openai-compatible",
  824. apiKey: "key",
  825. models: [
  826. {
  827. id: "glm-4.7",
  828. config: { optionSpecs: { reasoningLevel: { values: ["low", "high", "max"] } } },
  829. },
  830. ],
  831. createdAt: Date.now(),
  832. updatedAt: Date.now(),
  833. },
  834. ]),
  835. repo: repo as never,
  836. });
  837. const modelProviderReplies = await service.handleInboundMessage({
  838. botId: "weixin-1",
  839. text: "/model",
  840. actor: weixinActor,
  841. });
  842. expect(modelProviderReplies[0]?.text).toContain("Custom Provider");
  843. expect(modelProviderReplies[0]?.text).not.toContain("GPT-5.3, GPT-5.4");
  844. expect(modelProviderReplies[0]?.text).not.toContain("glm-4.7");
  845. await service.handleInboundMessage({
  846. botId: "weixin-1",
  847. text: "1",
  848. actor: weixinActor,
  849. });
  850. const modelReplies = await service.handleInboundMessage({
  851. botId: "weixin-1",
  852. text: "1",
  853. actor: weixinActor,
  854. });
  855. expect(modelReplies[0]?.text).not.toContain("未找到模型供应商");
  856. expect(modelReplies[0]?.text).toContain("工作区:");
  857. const modeReplies = await service.handleInboundMessage({
  858. botId: "weixin-1",
  859. text: "/mode",
  860. actor: weixinActor,
  861. });
  862. expect(modeReplies[0]?.text).toContain("yolo");
  863. expect(legacyTaskService.setModel).toHaveBeenCalledWith(
  864. expect.objectContaining({
  865. taskId: "task-1",
  866. modelSelection: {
  867. providerId: "custom-provider",
  868. modelId: "glm-4.7",
  869. options: { reasoningLevel: "max" },
  870. },
  871. }),
  872. );
  873. expect(legacyTaskService.setConfigOption).not.toHaveBeenCalledWith(
  874. expect.objectContaining({ configId: "mode" }),
  875. );
  876. expect(broadcastService.send).toHaveBeenCalledWith(
  877. expect.objectContaining({
  878. channel: "bots:task",
  879. payload: expect.objectContaining({
  880. taskId: "task-1",
  881. provider: "glm",
  882. configOptions: expect.arrayContaining([
  883. expect.objectContaining({ currentValue: "gpt-5.4" }),
  884. ]),
  885. }),
  886. }),
  887. );
  888. expect((await repo.readConfig()).bots[0]?.currentOptions).toEqual({});
  889. service.disposeAll();
  890. });
  891. it("passes only custom provider modelSelection when a remote Bot switches models", async () => {
  892. const providerId = "custom-provider-b";
  893. const modelId = "gpt-5.5";
  894. const repo = f.createMemoryRepo(f.weixinConfig, {
  895. version: 3,
  896. bots: {
  897. "weixin-1": {
  898. botId: "weixin-1",
  899. workspacePath: "/tmp/workspace",
  900. workspaceIdentity: "ssh://host/tmp/workspace",
  901. workspaceId: "ssh://host/tmp/workspace",
  902. mode: "task",
  903. activeTaskId: "task-1",
  904. updatedAt: Date.now(),
  905. },
  906. },
  907. });
  908. const legacyTaskService = f.createLegacyTaskService();
  909. const configOptions = [
  910. {
  911. id: "model",
  912. category: "model",
  913. type: "select" as const,
  914. currentValue: "glm-4.6",
  915. options: [{ value: "glm-4.6", name: "GLM 4.6" }],
  916. },
  917. ];
  918. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue(configOptions);
  919. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  920. {
  921. taskId: "task-1",
  922. title: "Active task",
  923. workspacePath: "/tmp/workspace",
  924. workspaceIdentity: "ssh://host/tmp/workspace",
  925. provider: "glm",
  926. model: "glm-4.6",
  927. status: "completed",
  928. },
  929. ]);
  930. vi.mocked(legacyTaskService.setModel).mockResolvedValue([
  931. {
  932. ...configOptions[0]!,
  933. currentValue: encodeCustomModelValue(providerId, modelId),
  934. },
  935. ]);
  936. const zcodeSessionService = Object.assign(
  937. f.createZCodeSessionService(f.createZCodeSessionSettingsFromConfigOptions(configOptions)),
  938. {
  939. updateProviderRegistry: vi.fn(async () => undefined),
  940. },
  941. );
  942. const service = f.createBotsService({
  943. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  944. legacyTaskService,
  945. zcodeSessionService,
  946. modelSelectionService: {
  947. getView: vi.fn(async () => ({
  948. revision: 1,
  949. providers: [
  950. {
  951. providerId,
  952. config: {
  953. kind: "api" as const,
  954. apiFormat: "openai-chat-completions" as const,
  955. baseURL: "https://example.com/v1",
  956. models: [modelId],
  957. },
  958. models: [
  959. {
  960. modelId,
  961. config: { optionSpecs: { reasoningLevel: { values: ["low", "high", "max"] } } },
  962. },
  963. ],
  964. },
  965. ],
  966. })),
  967. } as never,
  968. repo: repo as never,
  969. });
  970. const providerReplies = await service.handleInboundMessage({
  971. botId: "weixin-1",
  972. text: `/model provider ${providerId}`,
  973. actor: weixinActor,
  974. });
  975. expect(providerReplies[0]?.text).toContain("选择模型");
  976. await service.handleInboundMessage({
  977. botId: "weixin-1",
  978. text: "1",
  979. actor: weixinActor,
  980. });
  981. expect(zcodeSessionService.updateProviderRegistry).not.toHaveBeenCalled();
  982. expect(legacyTaskService.setModel).toHaveBeenCalledWith(
  983. expect.objectContaining({
  984. taskId: "task-1",
  985. modelSelection: { providerId, modelId, options: { reasoningLevel: "max" } },
  986. }),
  987. );
  988. service.disposeAll();
  989. });
  990. it("does not push the legacy provider snapshot when a local Bot switches models", async () => {
  991. const providerId = "local-registry-provider";
  992. const modelId = "gpt-5.6";
  993. const repo = f.createMemoryRepo(f.weixinConfig, {
  994. version: 3,
  995. bots: {
  996. "weixin-1": {
  997. botId: "weixin-1",
  998. workspacePath: "/tmp/workspace",
  999. workspaceId: "/tmp/workspace",
  1000. mode: "task",
  1001. activeTaskId: "task-1",
  1002. updatedAt: Date.now(),
  1003. },
  1004. },
  1005. });
  1006. const zcodeTaskService = f.createLegacyTaskService();
  1007. const configOptions = [
  1008. {
  1009. id: "model",
  1010. category: "model",
  1011. type: "select" as const,
  1012. currentValue: "glm-4.6",
  1013. options: [{ value: "glm-4.6", name: "GLM 4.6" }],
  1014. },
  1015. ];
  1016. vi.mocked(zcodeTaskService.getTaskConfigOptions).mockResolvedValue(configOptions);
  1017. vi.mocked(zcodeTaskService.listTasks).mockResolvedValue([
  1018. {
  1019. taskId: "task-1",
  1020. title: "Active task",
  1021. workspacePath: "/tmp/workspace",
  1022. provider: "glm",
  1023. model: "glm-4.6",
  1024. status: "completed",
  1025. },
  1026. ]);
  1027. vi.mocked(zcodeTaskService.setModel).mockResolvedValue(configOptions);
  1028. const zcodeSessionService = f.createZCodeSessionService();
  1029. const updateProviderRegistry = vi.mocked(zcodeSessionService.updateProviderRegistry);
  1030. const service = f.createBotsService({
  1031. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  1032. zcodeTaskService,
  1033. zcodeSessionService,
  1034. settingService: f.createSettingService({
  1035. locale: "zh-CN",
  1036. lastWorkspaceSession: [{ kind: "local", workspacePath: "/tmp/workspace" }],
  1037. }),
  1038. modelSelectionService: {
  1039. getView: vi.fn(async () => ({
  1040. revision: 9,
  1041. providers: [
  1042. {
  1043. providerId,
  1044. providerName: "Local Registry Provider",
  1045. config: {
  1046. api: { type: "openai-chat-completions", baseUrl: "https://example.com/v1" },
  1047. },
  1048. models: [
  1049. {
  1050. modelId,
  1051. config: { optionSpecs: { reasoningLevel: { values: ["low", "high", "max"] } } },
  1052. },
  1053. ],
  1054. },
  1055. ],
  1056. })),
  1057. } as never,
  1058. remoteWorkspaceService: undefined,
  1059. repo: repo as never,
  1060. });
  1061. const providerReplies = await service.handleInboundMessage({
  1062. botId: "weixin-1",
  1063. text: `/model provider ${providerId}`,
  1064. actor: weixinActor,
  1065. });
  1066. expect(providerReplies[0]?.text).toContain("选择模型");
  1067. const modelReplies = await service.handleInboundMessage({
  1068. botId: "weixin-1",
  1069. text: "1",
  1070. actor: weixinActor,
  1071. });
  1072. expect(modelReplies[0]?.text).toContain("工作区:");
  1073. expect(zcodeTaskService.setModel).toHaveBeenCalledWith(
  1074. expect.objectContaining({
  1075. taskId: "task-1",
  1076. modelSelection: { providerId, modelId, options: { reasoningLevel: "max" } },
  1077. }),
  1078. );
  1079. expect(updateProviderRegistry).not.toHaveBeenCalled();
  1080. service.disposeAll();
  1081. });
  1082. it("renders /mode labels after normalizing legacy task provider to ZCode Agent", async () => {
  1083. const repo = f.createMemoryRepo(f.weixinConfig, {
  1084. version: 3,
  1085. bots: {
  1086. "weixin-1": {
  1087. botId: "weixin-1",
  1088. workspacePath: "/tmp/workspace",
  1089. workspaceIdentity: "ssh://host/tmp/workspace",
  1090. workspaceId: "ssh://host/tmp/workspace",
  1091. mode: "task",
  1092. activeTaskId: "task-1",
  1093. updatedAt: Date.now(),
  1094. },
  1095. },
  1096. });
  1097. const legacyTaskService = f.createLegacyTaskService();
  1098. const configOptions = [
  1099. {
  1100. id: "mode",
  1101. category: "mode",
  1102. type: "select" as const,
  1103. currentValue: "agent",
  1104. options: [
  1105. { value: "read-only", name: "Read Only" },
  1106. { value: "auto", name: "Default" },
  1107. { value: "agent", name: "Agent" },
  1108. { value: "full-access", name: "Full Access" },
  1109. { value: "agent-full-access", name: "Agent (full access)" },
  1110. ],
  1111. },
  1112. ];
  1113. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue(configOptions);
  1114. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  1115. {
  1116. taskId: "task-1",
  1117. title: "Active task",
  1118. workspacePath: "/tmp/workspace",
  1119. workspaceIdentity: "ssh://host/tmp/workspace",
  1120. provider: "codex",
  1121. status: "completed",
  1122. },
  1123. ]);
  1124. const service = f.createBotsService({
  1125. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  1126. legacyTaskService,
  1127. settingService: f.createSettingService({
  1128. locale: "en-US",
  1129. lastWorkspaceSession: [
  1130. {
  1131. kind: "remote",
  1132. workspacePath: "/tmp/workspace",
  1133. workspaceIdentity: "ssh://host/tmp/workspace",
  1134. },
  1135. ],
  1136. }),
  1137. repo: repo as never,
  1138. });
  1139. const replies = await service.handleInboundMessage({
  1140. botId: "weixin-1",
  1141. text: "/mode",
  1142. actor: weixinActor,
  1143. });
  1144. expect(replies[0]?.text).toContain("yolo");
  1145. service.disposeAll();
  1146. });
  1147. it("loads /mode options from ZCode workspace state when active task has no mode option", async () => {
  1148. const repo = f.createMemoryRepo(f.weixinConfig, {
  1149. version: 3,
  1150. bots: {
  1151. "weixin-1": {
  1152. botId: "weixin-1",
  1153. workspacePath: "/tmp/workspace",
  1154. workspaceIdentity: "ssh://host/tmp/workspace",
  1155. workspaceId: "ssh://host/tmp/workspace",
  1156. mode: "task",
  1157. activeTaskId: "task-1",
  1158. updatedAt: Date.now(),
  1159. },
  1160. },
  1161. });
  1162. const legacyTaskService = f.createLegacyTaskService();
  1163. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([]);
  1164. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  1165. {
  1166. taskId: "task-1",
  1167. title: "Active task",
  1168. workspacePath: "/tmp/workspace",
  1169. workspaceIdentity: "ssh://host/tmp/workspace",
  1170. provider: "codex",
  1171. mode: "auto",
  1172. status: "completed",
  1173. },
  1174. ]);
  1175. const service = f.createBotsService({
  1176. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  1177. legacyTaskService,
  1178. settingService: f.createSettingService({
  1179. locale: "en-US",
  1180. lastWorkspaceSession: [
  1181. {
  1182. kind: "remote",
  1183. workspacePath: "/tmp/workspace",
  1184. workspaceIdentity: "ssh://host/tmp/workspace",
  1185. },
  1186. ],
  1187. }),
  1188. repo: repo as never,
  1189. });
  1190. const replies = await service.handleInboundMessage({
  1191. botId: "weixin-1",
  1192. text: "/mode",
  1193. actor: weixinActor,
  1194. });
  1195. expect(replies[0]?.text).toContain("yolo");
  1196. expect(legacyTaskService.setConfigOption).not.toHaveBeenCalledWith(
  1197. expect.objectContaining({ configId: "mode" }),
  1198. );
  1199. service.disposeAll();
  1200. });
  1201. it("keeps /think options tied to active task config", async () => {
  1202. const repo = f.createMemoryRepo(f.weixinConfig, {
  1203. version: 3,
  1204. bots: {
  1205. "weixin-1": {
  1206. botId: "weixin-1",
  1207. workspacePath: "/tmp/workspace",
  1208. workspaceIdentity: "ssh://host/tmp/workspace",
  1209. workspaceId: "ssh://host/tmp/workspace",
  1210. mode: "task",
  1211. activeTaskId: "task-1",
  1212. updatedAt: Date.now(),
  1213. },
  1214. },
  1215. });
  1216. const legacyTaskService = f.createLegacyTaskService();
  1217. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([]);
  1218. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  1219. {
  1220. taskId: "task-1",
  1221. title: "Active task",
  1222. workspacePath: "/tmp/workspace",
  1223. workspaceIdentity: "ssh://host/tmp/workspace",
  1224. provider: "codex",
  1225. status: "completed",
  1226. },
  1227. ]);
  1228. const service = f.createBotsService({
  1229. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  1230. legacyTaskService,
  1231. repo: repo as never,
  1232. });
  1233. const replies = await service.handleInboundMessage({
  1234. botId: "weixin-1",
  1235. text: "/think",
  1236. actor: weixinActor,
  1237. });
  1238. expect(replies[0]?.text).toContain("当前模型不支持思考级别");
  1239. expect(replies[0]?.text).not.toContain("Medium");
  1240. service.disposeAll();
  1241. });
  1242. it("loads local Bot model providers from Model Selection Service", async () => {
  1243. const repo = f.createMemoryRepo(f.weixinConfig, {
  1244. version: 3,
  1245. bots: {
  1246. "weixin-1": {
  1247. botId: "weixin-1",
  1248. workspacePath: "/tmp/workspace",
  1249. workspaceIdentity: "ssh://host/tmp/workspace",
  1250. workspaceId: "ssh://host/tmp/workspace",
  1251. mode: "task",
  1252. activeTaskId: "task-1",
  1253. updatedAt: Date.now(),
  1254. },
  1255. },
  1256. });
  1257. const legacyTaskService = f.createLegacyTaskService();
  1258. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([
  1259. {
  1260. id: "model",
  1261. category: "model",
  1262. type: "select" as const,
  1263. currentValue: "gpt-5.3",
  1264. options: [],
  1265. },
  1266. ]);
  1267. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  1268. {
  1269. taskId: "task-1",
  1270. title: "Active task",
  1271. workspacePath: "/tmp/workspace",
  1272. workspaceIdentity: "ssh://host/tmp/workspace",
  1273. provider: "glm",
  1274. model: "gpt-5.3",
  1275. status: "completed",
  1276. },
  1277. ]);
  1278. const zcodeSessionService = f.createZCodeSessionService(
  1279. f.createZCodeSessionSettingsFromConfigOptions([
  1280. {
  1281. id: "model",
  1282. category: "model",
  1283. type: "select" as const,
  1284. currentValue: "gpt-5.3",
  1285. options: [
  1286. {
  1287. value: "gpt-5.4",
  1288. name: "GPT-5.4",
  1289. modelProviderId: "glm",
  1290. modelProviderName: "ZCode Agent",
  1291. },
  1292. ],
  1293. },
  1294. ]),
  1295. );
  1296. const service = f.createBotsService({
  1297. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  1298. legacyTaskService,
  1299. zcodeSessionService,
  1300. modelSelectionService: {
  1301. getView: vi.fn(async () => ({
  1302. revision: 7,
  1303. providers: [
  1304. {
  1305. providerId: "runtime-provider",
  1306. providerName: "Runtime Provider",
  1307. config: {
  1308. api: { type: "openai-chat-completions", baseUrl: "https://example.com/v1" },
  1309. },
  1310. models: [
  1311. {
  1312. modelId: "gpt-5.4",
  1313. config: { optionSpecs: { reasoningLevel: { values: ["low", "high", "max"] } } },
  1314. },
  1315. ],
  1316. },
  1317. ],
  1318. })),
  1319. } as never,
  1320. repo: repo as never,
  1321. });
  1322. const replies = await service.handleInboundMessage({
  1323. botId: "weixin-1",
  1324. text: "/model",
  1325. actor: weixinActor,
  1326. });
  1327. expect(replies[0]?.text).toContain("Runtime Provider");
  1328. expect(replies[0]?.text).toContain("当前模型 gpt-5.3");
  1329. await service.handleInboundMessage({
  1330. botId: "weixin-1",
  1331. text: "1",
  1332. actor: weixinActor,
  1333. });
  1334. const modelReplies = await service.handleInboundMessage({
  1335. botId: "weixin-1",
  1336. text: "1",
  1337. actor: weixinActor,
  1338. });
  1339. expect(modelReplies[0]?.text).toContain("工作区:");
  1340. expect(legacyTaskService.setModel).toHaveBeenCalledWith(
  1341. expect.objectContaining({
  1342. taskId: "task-1",
  1343. modelSelection: {
  1344. providerId: "runtime-provider",
  1345. modelId: "gpt-5.4",
  1346. options: { reasoningLevel: "max" },
  1347. },
  1348. }),
  1349. );
  1350. service.disposeAll();
  1351. });
  1352. it("formats local Bot status labels from Model Selection Service", async () => {
  1353. const providerId = "runtime-provider";
  1354. const modelId = "gpt-5.4";
  1355. const repo = f.createMemoryRepo(f.weixinConfig, {
  1356. version: 3,
  1357. bots: {
  1358. "weixin-1": {
  1359. botId: "weixin-1",
  1360. workspacePath: "/tmp/workspace",
  1361. workspaceIdentity: "/tmp/workspace",
  1362. workspaceId: "/tmp/workspace",
  1363. mode: "draft",
  1364. activeTaskId: null,
  1365. draftOptions: {
  1366. provider: "glm",
  1367. modelSelection: { providerId, modelId },
  1368. },
  1369. updatedAt: Date.now(),
  1370. },
  1371. },
  1372. });
  1373. const service = f.createBotsService({
  1374. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  1375. legacyTaskService: f.createLegacyTaskService(),
  1376. modelSelectionService: {
  1377. getView: vi.fn(async () => ({
  1378. revision: 8,
  1379. effectiveSelection: { providerId, modelId },
  1380. providers: [
  1381. {
  1382. providerId,
  1383. providerName: "Registry Label",
  1384. config: {
  1385. api: {
  1386. type: "openai-chat-completions",
  1387. baseUrl: "https://registry.example.com/v1",
  1388. },
  1389. },
  1390. models: [{ modelId, config: {} }],
  1391. },
  1392. ],
  1393. })),
  1394. } as never,
  1395. repo: repo as never,
  1396. });
  1397. const replies = await service.handleInboundMessage({
  1398. botId: "weixin-1",
  1399. text: "/status",
  1400. actor: weixinActor,
  1401. });
  1402. expect(replies[0]?.text).toContain(`模型: Registry Label/${modelId}`);
  1403. service.disposeAll();
  1404. });
  1405. it("ignores persisted legacy Provider cache and uses Model Selection View", async () => {
  1406. const workspacePath = "/tmp/workspace";
  1407. const workspaceIdentity = "ssh://host/tmp/workspace";
  1408. const repo = f.createMemoryRepo(f.weixinConfig, {
  1409. version: 3,
  1410. bots: {
  1411. "weixin-1": {
  1412. botId: "weixin-1",
  1413. workspacePath,
  1414. workspaceIdentity,
  1415. workspaceId: workspaceIdentity,
  1416. mode: "task",
  1417. activeTaskId: "task-1",
  1418. updatedAt: Date.now(),
  1419. },
  1420. },
  1421. });
  1422. const legacyTaskService = f.createLegacyTaskService();
  1423. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  1424. {
  1425. taskId: "task-1",
  1426. title: "Active task",
  1427. workspacePath,
  1428. workspaceIdentity,
  1429. provider: "codex",
  1430. model: "cached-native",
  1431. status: "completed",
  1432. },
  1433. ]);
  1434. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([
  1435. {
  1436. id: "model",
  1437. category: "model",
  1438. type: "select" as const,
  1439. currentValue: "cached-native",
  1440. options: [],
  1441. },
  1442. ]);
  1443. const service = f.createBotsService({
  1444. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  1445. legacyTaskService,
  1446. modelSelectionService: f.createModelSelectionService([
  1447. {
  1448. id: "cached-custom",
  1449. name: "Cached Provider",
  1450. endpoints: {
  1451. baseURL: "https://example.com/v1",
  1452. paths: { "openai-compatible": "" },
  1453. },
  1454. defaultKind: "openai-compatible",
  1455. apiKey: "real-key",
  1456. models: ["cached-custom-model"],
  1457. createdAt: Date.now(),
  1458. updatedAt: Date.now(),
  1459. },
  1460. ]),
  1461. repo: repo as never,
  1462. });
  1463. const providerReplies = await service.handleInboundMessage({
  1464. botId: "weixin-1",
  1465. text: "/model",
  1466. actor: weixinActor,
  1467. });
  1468. expect(providerReplies[0]?.text).not.toContain("Cached Native");
  1469. expect(providerReplies[0]?.text).not.toContain("cached-custom-model");
  1470. expect(providerReplies[0]?.text).toContain("Cached Provider");
  1471. const modelReplies = await service.handleInboundMessage({
  1472. botId: "weixin-1",
  1473. text: "1",
  1474. actor: weixinActor,
  1475. });
  1476. expect(modelReplies[0]?.text).toContain("cached-custom-model");
  1477. service.disposeAll();
  1478. });
  1479. it("does not resolve Feishu model provider clicks from the persisted model cache", async () => {
  1480. const workspacePath = "/tmp/workspace";
  1481. const workspaceIdentity = "ssh://host/tmp/workspace";
  1482. const providerId = "693f9c23-72a5-4f1f-bf4a-4b958add6472";
  1483. const modelId = "deepseek-v4-flash";
  1484. const repo = f.createMemoryRepo(f.feishuConfig, {
  1485. version: 3,
  1486. bots: {
  1487. "feishu-1": {
  1488. botId: "feishu-1",
  1489. workspacePath,
  1490. workspaceIdentity,
  1491. workspaceId: workspaceIdentity,
  1492. mode: "draft",
  1493. activeTaskId: null,
  1494. draftOptions: {
  1495. provider: "glm",
  1496. model: encodeCustomModelValue(providerId, modelId),
  1497. },
  1498. updatedAt: Date.now(),
  1499. },
  1500. },
  1501. });
  1502. const service = f.createBotsService({
  1503. credentialService: f.createCredentialService({
  1504. "feishu-secret": "secret",
  1505. }),
  1506. repo: repo as never,
  1507. });
  1508. const replies = await service.handleInboundMessage({
  1509. botId: "feishu-1",
  1510. text: `/model provider ${providerId}`,
  1511. actor: feishuActor,
  1512. });
  1513. expect(replies[0]?.text).toContain("未找到模型供应商");
  1514. expect(replies[0]?.selection).toBeUndefined();
  1515. service.disposeAll();
  1516. });
  1517. it("uses the same compact selection text for Feishu and Telegram native buttons", async () => {
  1518. const repo = f.createMemoryRepo(f.feishuConfig);
  1519. const service = f.createBotsService({
  1520. legacyTaskService: f.createLegacyTaskService(),
  1521. credentialService: f.createCredentialService({
  1522. "feishu-secret": "secret",
  1523. }),
  1524. repo: repo as never,
  1525. });
  1526. const replies = await service.handleInboundMessage({
  1527. botId: "feishu-1",
  1528. text: "/workspace",
  1529. actor: feishuActor,
  1530. });
  1531. expect(replies[0]).toMatchObject({
  1532. provider: "feishu",
  1533. providerUserId: "ou_user",
  1534. selection: expect.objectContaining({ action: "workspace.set" }),
  1535. });
  1536. expect(replies[0]?.text).toContain("选择 workspace");
  1537. expect(replies[0]?.text).not.toContain("/workspace");
  1538. service.disposeAll();
  1539. });
  1540. it("creates an ZCode Agent task from a bound private message", async () => {
  1541. const repo = f.createMemoryRepo(f.baseConfig);
  1542. const legacyTaskService = f.createLegacyTaskService();
  1543. const broadcastService = f.createBroadcastService();
  1544. const service = f.createBotsService({
  1545. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  1546. legacyTaskService,
  1547. broadcastService,
  1548. repo: repo as never,
  1549. });
  1550. await bind(service);
  1551. const replies = await service.handleInboundMessage({
  1552. botId: "webhook-1",
  1553. text: "请检查当前项目",
  1554. actor,
  1555. });
  1556. expect(replies).toEqual([]);
  1557. expect(legacyTaskService.createTask).toHaveBeenCalledWith(
  1558. expect.objectContaining({
  1559. workspacePath: "/tmp/workspace",
  1560. workspaceIdentity: "ssh://host/tmp/workspace",
  1561. provider: "glm",
  1562. modelSelection: { providerId: "glm", modelId: "default" },
  1563. v4Create: true,
  1564. }),
  1565. );
  1566. expect(legacyTaskService.sendPrompt).toHaveBeenCalledWith(
  1567. expect.objectContaining({ content: "请检查当前项目" }),
  1568. );
  1569. expect((await repo.readState()).bots["webhook-1"]).toMatchObject({
  1570. activeTaskId: "task-1",
  1571. mode: "task",
  1572. workspaceIdentity: "ssh://host/tmp/workspace",
  1573. });
  1574. expect(broadcastService.send).toHaveBeenCalledWith(
  1575. expect.objectContaining({
  1576. channel: "bots:task",
  1577. payload: expect.objectContaining({
  1578. event: "created",
  1579. taskId: "task-1",
  1580. }),
  1581. }),
  1582. );
  1583. service.disposeAll();
  1584. });
  1585. it("resolves an unfixed Bot draft from the target Host only when the message forms a Submission", async () => {
  1586. const repo = f.createMemoryRepo(f.baseConfig);
  1587. const legacyTaskService = f.createLegacyTaskService();
  1588. const remoteModelSelectionService = f.createModelSelectionService([
  1589. { id: "remote-provider", name: "Remote", models: ["model-a"] },
  1590. ]);
  1591. const service = f.createBotsService({
  1592. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  1593. legacyTaskService,
  1594. remoteWorkspaceService: {
  1595. isConnected: vi.fn(async () => true),
  1596. ensureConnected: vi.fn(async () => ({ ok: true })),
  1597. getZCodeTaskService: vi.fn(async () => legacyTaskService),
  1598. getModelSelectionService: vi.fn(async () => remoteModelSelectionService),
  1599. },
  1600. repo: repo as never,
  1601. });
  1602. await bind(service);
  1603. vi.mocked(remoteModelSelectionService.getView).mockResolvedValue({
  1604. revision: 2,
  1605. providers: [
  1606. {
  1607. providerId: "remote-provider",
  1608. providerName: "Remote",
  1609. config: {},
  1610. models: [{ modelId: "model-b", config: {} }],
  1611. },
  1612. ],
  1613. preferredSelection: { providerId: "remote-provider", modelId: "model-b" },
  1614. });
  1615. await service.handleInboundMessage({
  1616. botId: "webhook-1",
  1617. text: "use the submission-time model",
  1618. actor,
  1619. });
  1620. expect(legacyTaskService.createTask).toHaveBeenCalledWith(
  1621. expect.objectContaining({
  1622. modelSelection: { providerId: "remote-provider", modelId: "model-b" },
  1623. }),
  1624. );
  1625. service.disposeAll();
  1626. });
  1627. it("injects a Feishu delivery target into the prompt that may call CronCreate", async () => {
  1628. const repo = f.createMemoryRepo(f.feishuConfig);
  1629. const legacyTaskService = f.createLegacyTaskService();
  1630. const service = f.createBotsService({
  1631. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  1632. legacyTaskService,
  1633. repo: repo as never,
  1634. });
  1635. await service.handleInboundMessage({
  1636. botId: "feishu-1",
  1637. text: "每天九点生成日报",
  1638. actor: feishuActor,
  1639. });
  1640. expect(legacyTaskService.sendPrompt).toHaveBeenCalledWith(
  1641. expect.objectContaining({
  1642. botDeliveryTarget: {
  1643. provider: "feishu",
  1644. botId: "feishu-1",
  1645. providerUserId: "ou_user",
  1646. chatType: "private",
  1647. },
  1648. }),
  1649. );
  1650. service.disposeAll();
  1651. });
  1652. it("delivers an automation terminal result through the original Weixin bot channel", async () => {
  1653. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ret: 0 }), { status: 200 }));
  1654. vi.stubGlobal("fetch", fetchMock);
  1655. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  1656. const legacyTaskService = {
  1657. ...f.createLegacyTaskService(),
  1658. onDynamicTaskEvent: vi.fn(
  1659. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  1660. streamListeners.push(listener);
  1661. return { dispose() {} };
  1662. },
  1663. ),
  1664. };
  1665. const service = f.createBotsService({
  1666. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  1667. legacyTaskService,
  1668. repo: f.createMemoryRepo(f.weixinConfig) as never,
  1669. });
  1670. await service.watchAutomationRun({
  1671. target: {
  1672. provider: "weixin",
  1673. botId: "weixin-1",
  1674. providerUserId: "wx_chat_1",
  1675. chatType: "private",
  1676. },
  1677. taskId: "task-automation-1",
  1678. workspacePath: "/tmp/workspace",
  1679. workspaceIdentity: "ssh://host/tmp/workspace",
  1680. });
  1681. expect(legacyTaskService.onDynamicTaskEvent).toHaveBeenCalledWith(
  1682. expect.objectContaining({
  1683. taskId: "task-automation-1",
  1684. deliveryKind: "bot-channel-continuous",
  1685. }),
  1686. );
  1687. await streamListeners[0]?.({
  1688. type: "agent_message_chunk",
  1689. taskId: "task-automation-1",
  1690. traceId: "automation-run-1",
  1691. content: "日报已生成。",
  1692. });
  1693. await streamListeners[0]?.({
  1694. type: "task_complete",
  1695. taskId: "task-automation-1",
  1696. traceId: "automation-run-1",
  1697. stopReason: "end_turn",
  1698. });
  1699. const sendCall = fetchMock.mock.calls.find(([url]) =>
  1700. String(url).includes("/ilink/bot/sendmessage"),
  1701. );
  1702. expect(sendCall).toBeDefined();
  1703. expect(String(sendCall?.[1]?.body)).toContain("日报已生成");
  1704. service.disposeAll();
  1705. });
  1706. it.each([
  1707. {
  1708. name: "missing bot",
  1709. config: { ...f.feishuConfig, bots: [] },
  1710. target: { ...feishuActor, botId: "missing-bot" },
  1711. },
  1712. {
  1713. name: "disabled bot",
  1714. config: {
  1715. ...f.feishuConfig,
  1716. bots: f.feishuConfig.bots.map((bot) => ({ ...bot, enabled: false })),
  1717. },
  1718. target: feishuActor,
  1719. },
  1720. {
  1721. name: "provider mismatch",
  1722. config: f.feishuConfig,
  1723. target: { ...feishuActor, provider: "weixin" as const },
  1724. },
  1725. ])(
  1726. "skips automation delivery without opening a task watcher for $name",
  1727. async ({ config, target }) => {
  1728. const legacyTaskService = {
  1729. ...f.createLegacyTaskService(),
  1730. onDynamicTaskEvent: vi.fn(),
  1731. };
  1732. const service = f.createBotsService({
  1733. legacyTaskService,
  1734. repo: f.createMemoryRepo(config) as never,
  1735. });
  1736. // Bot 配置可能在任务创建后被删除、禁用或改成其他 provider;这些变化只跳过回推,
  1737. // 不能建立无效监听,更不能让 scheduler 的桌面执行失败。
  1738. await expect(
  1739. service.watchAutomationRun({
  1740. target,
  1741. taskId: "task-automation-skipped",
  1742. workspacePath: "/tmp/workspace",
  1743. }),
  1744. ).resolves.toBeUndefined();
  1745. expect(legacyTaskService.onDynamicTaskEvent).not.toHaveBeenCalled();
  1746. service.disposeAll();
  1747. },
  1748. );
  1749. it("sends channel replies from workspace task mirror batches", async () => {
  1750. const fetchMock = vi.fn(
  1751. async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
  1752. );
  1753. vi.stubGlobal("fetch", fetchMock);
  1754. const repo = f.createMemoryRepo({
  1755. ...f.baseConfig,
  1756. bots: [
  1757. {
  1758. ...f.baseConfig.bots[0]!,
  1759. webhookUrl: "https://example.test/zcode-bot-outbound",
  1760. },
  1761. ],
  1762. });
  1763. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  1764. const legacyTaskService = {
  1765. ...f.createLegacyTaskService(),
  1766. onDynamicTaskEvent: vi.fn(
  1767. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  1768. streamListeners.push(listener);
  1769. return { dispose() {} };
  1770. },
  1771. ),
  1772. };
  1773. const broadcastService = f.createBroadcastService();
  1774. const service = f.createBotsService({
  1775. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  1776. legacyTaskService,
  1777. broadcastService,
  1778. repo: repo as never,
  1779. });
  1780. await bind(service);
  1781. await service.handleInboundMessage({
  1782. botId: "webhook-1",
  1783. text: "请检查当前项目",
  1784. actor,
  1785. });
  1786. expect(legacyTaskService.onDynamicTaskEvent).toHaveBeenCalledWith(
  1787. expect.objectContaining({
  1788. workspacePath: "/tmp/workspace",
  1789. workspaceIdentity: "ssh://host/tmp/workspace",
  1790. taskId: "task-1",
  1791. deliveryKind: "bot-channel-continuous",
  1792. }),
  1793. );
  1794. await streamListeners[0]?.({
  1795. type: "task_stream_mirror_batch",
  1796. workspacePath: "/tmp/workspace",
  1797. workspaceIdentity: "ssh://host/tmp/workspace",
  1798. workspaceKey: "ssh://host/tmp/workspace",
  1799. taskId: "task-1",
  1800. traceId: "trace-1",
  1801. runId: "run-1",
  1802. batchSeq: 1,
  1803. fromSeq: 1,
  1804. toSeq: 2,
  1805. terminal: true,
  1806. ops: [
  1807. {
  1808. seq: 1,
  1809. kind: "stream_event",
  1810. event: {
  1811. type: "agent_message_chunk",
  1812. taskId: "task-1",
  1813. traceId: "trace-1",
  1814. content: "完成了。",
  1815. },
  1816. },
  1817. {
  1818. seq: 2,
  1819. kind: "stream_event",
  1820. event: {
  1821. type: "task_complete",
  1822. taskId: "task-1",
  1823. traceId: "trace-1",
  1824. stopReason: "end_turn",
  1825. },
  1826. },
  1827. ],
  1828. });
  1829. expect(fetchMock).toHaveBeenCalledWith(
  1830. "https://example.test/zcode-bot-outbound",
  1831. expect.objectContaining({
  1832. method: "POST",
  1833. body: expect.stringContaining("完成了。"),
  1834. }),
  1835. );
  1836. service.disposeAll();
  1837. });
  1838. it("streams Feishu replies into one schema 2 timeline card with collapsed tool summaries", async () => {
  1839. const fetchMock = vi.fn(async (url: string) => {
  1840. if (url.endsWith("/tenant_access_token/internal")) {
  1841. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  1842. }
  1843. if (String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id")) {
  1844. return new Response(JSON.stringify({ code: 0, data: { message_id: "om_streaming" } }));
  1845. }
  1846. return new Response(JSON.stringify({ code: 0 }));
  1847. });
  1848. vi.stubGlobal("fetch", fetchMock);
  1849. const repo = f.createMemoryRepo({
  1850. ...f.feishuConfig,
  1851. bots: [
  1852. {
  1853. ...f.feishuConfig.bots[0]!,
  1854. replyMode: "streaming_card",
  1855. },
  1856. ],
  1857. });
  1858. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  1859. const legacyTaskService = {
  1860. ...f.createLegacyTaskService(),
  1861. onDynamicTaskEvent: vi.fn(
  1862. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  1863. streamListeners.push(listener);
  1864. return { dispose() {} };
  1865. },
  1866. ),
  1867. };
  1868. const service = f.createBotsService({
  1869. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  1870. legacyTaskService,
  1871. repo: repo as never,
  1872. });
  1873. await service.handleInboundMessage({
  1874. botId: "feishu-1",
  1875. text: "请检查当前项目",
  1876. actor: feishuActor,
  1877. });
  1878. await streamListeners[0]?.({
  1879. type: "agent_message_chunk",
  1880. taskId: "task-1",
  1881. traceId: "trace-1",
  1882. content: "我先检查项目。",
  1883. });
  1884. await streamListeners[0]?.({
  1885. type: "tool_call",
  1886. taskId: "task-1",
  1887. traceId: "trace-1",
  1888. toolId: "tool-1",
  1889. title: "Read README.md",
  1890. kind: "read",
  1891. input: { path: "/tmp/workspace/README.md" },
  1892. raw: {},
  1893. });
  1894. await streamListeners[0]?.({
  1895. type: "tool_call_update",
  1896. taskId: "task-1",
  1897. traceId: "trace-1",
  1898. toolId: "tool-1",
  1899. status: "completed",
  1900. title: "Read README.md",
  1901. kind: "read",
  1902. content: "ok",
  1903. raw: {},
  1904. });
  1905. await streamListeners[0]?.({
  1906. type: "agent_message_chunk",
  1907. taskId: "task-1",
  1908. traceId: "trace-1",
  1909. content: "README 看完了,我再跑测试。",
  1910. });
  1911. await streamListeners[0]?.({
  1912. type: "tool_call",
  1913. taskId: "task-1",
  1914. traceId: "trace-1",
  1915. toolId: "tool-2",
  1916. title: "pnpm test",
  1917. kind: "exec",
  1918. input: { command: "pnpm test" },
  1919. raw: {},
  1920. });
  1921. await streamListeners[0]?.({
  1922. type: "tool_call_update",
  1923. taskId: "task-1",
  1924. traceId: "trace-1",
  1925. toolId: "tool-2",
  1926. status: "completed",
  1927. title: "pnpm test",
  1928. kind: "exec",
  1929. content: "ok",
  1930. raw: {},
  1931. });
  1932. await streamListeners[0]?.({
  1933. type: "agent_message_chunk",
  1934. taskId: "task-1",
  1935. traceId: "trace-1",
  1936. content: "测试完成。",
  1937. });
  1938. await streamListeners[0]?.({
  1939. type: "task_complete",
  1940. taskId: "task-1",
  1941. traceId: "trace-1",
  1942. stopReason: "end_turn",
  1943. });
  1944. const messagePosts = fetchMock.mock.calls.filter(([url]) =>
  1945. String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id"),
  1946. );
  1947. const messagePatches = fetchMock.mock.calls.filter(([url]) =>
  1948. String(url).includes("/open-apis/im/v1/messages/om_streaming"),
  1949. );
  1950. expect(messagePosts).toHaveLength(1);
  1951. expect(messagePatches.length).toBeGreaterThanOrEqual(2);
  1952. const runningToolPatch = messagePatches.find(([, init]) =>
  1953. String(init?.body).includes("工具摘要"),
  1954. );
  1955. const runningBody = JSON.parse(String(runningToolPatch?.[1]?.body)) as { content?: string };
  1956. const runningCard = JSON.parse(String(runningBody.content)) as Record<string, unknown>;
  1957. expect(runningCard).toMatchObject({
  1958. schema: "2.0",
  1959. body: {
  1960. elements: expect.arrayContaining([
  1961. expect.objectContaining({
  1962. tag: "collapsible_panel",
  1963. expanded: true,
  1964. background_color: "grey-50",
  1965. border: { color: "grey", corner_radius: "8px" },
  1966. header: expect.objectContaining({
  1967. vertical_align: "center",
  1968. icon: expect.objectContaining({
  1969. tag: "standard_icon",
  1970. }),
  1971. icon_position: "right",
  1972. icon_expanded_angle: -180,
  1973. }),
  1974. }),
  1975. ]),
  1976. },
  1977. });
  1978. const finalPatch = messagePatches.at(-1);
  1979. const body = JSON.parse(String(finalPatch?.[1]?.body)) as { content?: string };
  1980. const card = JSON.parse(String(body.content)) as Record<string, unknown>;
  1981. expect(card).toMatchObject({
  1982. schema: "2.0",
  1983. body: {
  1984. elements: expect.arrayContaining([
  1985. expect.objectContaining({
  1986. tag: "collapsible_panel",
  1987. expanded: false,
  1988. background_color: "grey-50",
  1989. border: { color: "grey", corner_radius: "8px" },
  1990. header: expect.objectContaining({
  1991. vertical_align: "center",
  1992. icon: expect.objectContaining({
  1993. tag: "standard_icon",
  1994. }),
  1995. icon_position: "right",
  1996. icon_expanded_angle: -180,
  1997. }),
  1998. }),
  1999. expect.objectContaining({ tag: "markdown", content: "✅ 已完成" }),
  2000. ]),
  2001. },
  2002. });
  2003. expect(JSON.stringify(card)).toContain("我先检查项目。");
  2004. const elements = (card.body as { elements?: Array<Record<string, unknown>> }).elements ?? [];
  2005. const timeline = elements.map((element) =>
  2006. element.tag === "collapsible_panel"
  2007. ? `tools:${String((element.header as { title?: { content?: string } }).title?.content)}:${String(element.expanded)}`
  2008. : `message:${String(element.content)}`,
  2009. );
  2010. expect(timeline).toEqual([
  2011. "message:我先检查项目。",
  2012. "tools:🛠️ 工具摘要 (1):false",
  2013. "message:README 看完了,我再跑测试。",
  2014. "tools:🛠️ 工具摘要 (1):false",
  2015. "message:测试完成。",
  2016. "message:✅ 已完成",
  2017. ]);
  2018. expect(JSON.stringify(card)).toContain("✅ 已完成");
  2019. service.disposeAll();
  2020. });
  2021. it("backs off failed Feishu card writes and keeps the circuit open for late events", async () => {
  2022. vi.useFakeTimers();
  2023. try {
  2024. vi.setSystemTime(0);
  2025. const fetchMock = vi.fn(async (url: string) => {
  2026. if (url.endsWith("/tenant_access_token/internal")) {
  2027. return new Response(
  2028. JSON.stringify({
  2029. code: 0,
  2030. tenant_access_token: "tenant-token",
  2031. }),
  2032. );
  2033. }
  2034. return new Response(
  2035. JSON.stringify({
  2036. code: 230020,
  2037. msg: "Bot has NO availability to this user.",
  2038. }),
  2039. { status: 400 },
  2040. );
  2041. });
  2042. vi.stubGlobal("fetch", fetchMock);
  2043. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2044. const service = f.createBotsService({
  2045. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  2046. legacyTaskService: {
  2047. ...f.createLegacyTaskService(),
  2048. onDynamicTaskEvent: vi.fn(
  2049. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2050. streamListeners.push(listener);
  2051. return { dispose() {} };
  2052. },
  2053. ),
  2054. },
  2055. repo: f.createMemoryRepo({
  2056. ...f.feishuConfig,
  2057. bots: [{ ...f.feishuConfig.bots[0]!, replyMode: "streaming_card" }],
  2058. }) as never,
  2059. });
  2060. await service.handleInboundMessage({
  2061. botId: "feishu-1",
  2062. text: "请检查当前项目",
  2063. actor: feishuActor,
  2064. });
  2065. const emitChunk = async (content: string) =>
  2066. streamListeners[0]?.({
  2067. type: "agent_message_chunk",
  2068. taskId: "task-1",
  2069. traceId: "trace-1",
  2070. content,
  2071. });
  2072. await emitChunk("第一次");
  2073. vi.setSystemTime(1_000);
  2074. await emitChunk("第二次");
  2075. vi.setSystemTime(3_000);
  2076. await emitChunk("第三次");
  2077. vi.setSystemTime(20 * 60_000 + 3_000);
  2078. await emitChunk("停止二十分钟后的迟到事件");
  2079. const cardWrites = fetchMock.mock.calls.filter(([url]) =>
  2080. String(url).includes("/open-apis/im/v1/messages"),
  2081. );
  2082. expect(cardWrites).toHaveLength(3);
  2083. const runtime = (await service.getStatus()).botRuntime.find(
  2084. (entry) => entry.botId === "feishu-1",
  2085. );
  2086. expect(runtime?.deliveryError).toContain("code=230020");
  2087. expect(runtime?.status).not.toBe("error");
  2088. service.disposeAll();
  2089. } finally {
  2090. vi.useRealTimers();
  2091. }
  2092. });
  2093. it("does not retry an uncertain Feishu creation without a message id", async () => {
  2094. vi.useFakeTimers();
  2095. try {
  2096. vi.setSystemTime(0);
  2097. let messagePostCount = 0;
  2098. const fetchMock = vi.fn(async (url: string) => {
  2099. if (url.endsWith("/tenant_access_token/internal")) {
  2100. return new Response(
  2101. JSON.stringify({
  2102. code: 0,
  2103. tenant_access_token: "tenant-token",
  2104. }),
  2105. );
  2106. }
  2107. if (url.includes("/open-apis/im/v1/messages?receive_id_type=open_id")) {
  2108. messagePostCount += 1;
  2109. return new Response(
  2110. JSON.stringify({
  2111. code: 0,
  2112. data: messagePostCount === 1 ? {} : { message_id: "om_streaming_retry" },
  2113. }),
  2114. );
  2115. }
  2116. return new Response(JSON.stringify({ code: 0 }));
  2117. });
  2118. vi.stubGlobal("fetch", fetchMock);
  2119. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2120. const service = f.createBotsService({
  2121. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  2122. legacyTaskService: {
  2123. ...f.createLegacyTaskService(),
  2124. onDynamicTaskEvent: vi.fn(
  2125. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2126. streamListeners.push(listener);
  2127. return { dispose() {} };
  2128. },
  2129. ),
  2130. },
  2131. repo: f.createMemoryRepo({
  2132. ...f.feishuConfig,
  2133. bots: [{ ...f.feishuConfig.bots[0]!, replyMode: "streaming_card" }],
  2134. }) as never,
  2135. });
  2136. await service.handleInboundMessage({
  2137. botId: "feishu-1",
  2138. text: "请检查当前项目",
  2139. actor: feishuActor,
  2140. });
  2141. const emitChunk = async (content: string) =>
  2142. streamListeners[0]?.({
  2143. type: "agent_message_chunk",
  2144. taskId: "task-1",
  2145. traceId: "trace-no-message-id",
  2146. content,
  2147. });
  2148. await emitChunk("第一次");
  2149. vi.setSystemTime(500);
  2150. await emitChunk("退避期间不应重试");
  2151. expect(messagePostCount).toBe(1);
  2152. vi.setSystemTime(1_000);
  2153. await emitChunk("结果未知时不应自动重试");
  2154. expect(messagePostCount).toBe(1);
  2155. service.disposeAll();
  2156. } finally {
  2157. vi.useRealTimers();
  2158. }
  2159. });
  2160. it("seals a full Feishu streaming card and continues the timeline in a new card", async () => {
  2161. let messageId = 0;
  2162. const fetchMock = vi.fn(async (url: string) => {
  2163. if (url.endsWith("/tenant_access_token/internal")) {
  2164. return new Response(
  2165. JSON.stringify({
  2166. code: 0,
  2167. tenant_access_token: "tenant-token",
  2168. }),
  2169. );
  2170. }
  2171. if (url.includes("/open-apis/im/v1/messages?receive_id_type=open_id")) {
  2172. messageId += 1;
  2173. return new Response(
  2174. JSON.stringify({
  2175. code: 0,
  2176. data: { message_id: `om_streaming_${messageId}` },
  2177. }),
  2178. );
  2179. }
  2180. return new Response(JSON.stringify({ code: 0 }));
  2181. });
  2182. vi.stubGlobal("fetch", fetchMock);
  2183. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2184. const service = f.createBotsService({
  2185. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  2186. legacyTaskService: {
  2187. ...f.createLegacyTaskService(),
  2188. onDynamicTaskEvent: vi.fn(
  2189. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2190. streamListeners.push(listener);
  2191. return { dispose() {} };
  2192. },
  2193. ),
  2194. },
  2195. repo: f.createMemoryRepo({
  2196. ...f.feishuConfig,
  2197. bots: [{ ...f.feishuConfig.bots[0]!, replyMode: "streaming_card" }],
  2198. }) as never,
  2199. });
  2200. await service.handleInboundMessage({
  2201. botId: "feishu-1",
  2202. text: "请执行长任务",
  2203. actor: feishuActor,
  2204. });
  2205. for (let index = 0; index < 46; index += 1) {
  2206. await streamListeners[0]?.({
  2207. type: "agent_message_chunk",
  2208. taskId: "task-1",
  2209. traceId: "trace-limit",
  2210. content: `message-${index}`,
  2211. });
  2212. await streamListeners[0]?.({
  2213. type: "tool_call",
  2214. taskId: "task-1",
  2215. traceId: "trace-limit",
  2216. toolId: `tool-${index}`,
  2217. title: `Read file ${index}`,
  2218. kind: "read",
  2219. input: { path: `/tmp/workspace/${index}.txt` },
  2220. raw: {},
  2221. });
  2222. }
  2223. await streamListeners[0]?.({
  2224. type: "task_complete",
  2225. taskId: "task-1",
  2226. traceId: "trace-limit",
  2227. stopReason: "end_turn",
  2228. });
  2229. const messagePosts = fetchMock.mock.calls.filter(([url]) =>
  2230. String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id"),
  2231. );
  2232. expect(messagePosts).toHaveLength(2);
  2233. const secondCardWrites = fetchMock.mock.calls.filter(([url]) =>
  2234. String(url).includes("/open-apis/im/v1/messages/om_streaming_2"),
  2235. );
  2236. const secondBody = JSON.parse(String(secondCardWrites.at(-1)?.[1]?.body)) as {
  2237. content?: string;
  2238. };
  2239. expect(String(secondBody.content)).toContain("message-45");
  2240. expect(String(secondBody.content)).not.toContain("message-0");
  2241. service.disposeAll();
  2242. });
  2243. it("seals the current stream, retains Plan approval, and starts a new stream card", async () => {
  2244. let messagePostCount = 0;
  2245. const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
  2246. if (url.endsWith("/tenant_access_token/internal")) {
  2247. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2248. }
  2249. if (url.includes("/open-apis/im/v1/messages?receive_id_type=open_id")) {
  2250. messagePostCount += 1;
  2251. return new Response(
  2252. JSON.stringify({
  2253. code: 0,
  2254. data: {
  2255. message_id: messagePostCount === 1 ? "om_streaming" : "om_interaction",
  2256. },
  2257. }),
  2258. );
  2259. }
  2260. if (init?.method === "DELETE") {
  2261. return new Response(JSON.stringify({ code: 0 }));
  2262. }
  2263. return new Response(JSON.stringify({ code: 0 }));
  2264. });
  2265. vi.stubGlobal("fetch", fetchMock);
  2266. const repo = f.createMemoryRepo({
  2267. ...f.feishuConfig,
  2268. bots: [{ ...f.feishuConfig.bots[0]!, replyMode: "streaming_card" }],
  2269. });
  2270. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2271. const service = f.createBotsService({
  2272. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  2273. legacyTaskService: {
  2274. ...f.createLegacyTaskService(),
  2275. onDynamicTaskEvent: vi.fn(
  2276. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2277. streamListeners.push(listener);
  2278. return { dispose() {} };
  2279. },
  2280. ),
  2281. },
  2282. repo: repo as never,
  2283. });
  2284. await service.handleInboundMessage({
  2285. botId: "feishu-1",
  2286. text: "start",
  2287. actor: feishuActor,
  2288. });
  2289. await streamListeners[0]?.({
  2290. type: "agent_message_chunk",
  2291. taskId: "task-1",
  2292. traceId: "trace-1",
  2293. content: "正在制定计划。",
  2294. });
  2295. await streamListeners[0]?.({
  2296. type: "elicitation_request",
  2297. taskId: "task-1",
  2298. traceId: "trace-plan",
  2299. requestId: "plan-1",
  2300. message: "Review this implementation plan.",
  2301. options: [{ value: "approve", label: "Approve" }],
  2302. schema: {
  2303. interaction: "plan_approval",
  2304. plan: "# Plan\n\nBuild the board.",
  2305. },
  2306. });
  2307. expect(messagePostCount).toBe(2);
  2308. const sealedStreamUpdate = fetchMock.mock.calls.find(
  2309. ([url, init]) =>
  2310. String(url).includes("/open-apis/im/v1/messages/om_streaming") && init?.method === "PATCH",
  2311. );
  2312. expect(sealedStreamUpdate).toBeDefined();
  2313. expect(String(sealedStreamUpdate?.[1]?.body)).not.toContain("运行中");
  2314. const interactionPost = fetchMock.mock.calls
  2315. .filter(([url]) => String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id"))
  2316. .at(-1);
  2317. const interactionBody = JSON.parse(String(interactionPost?.[1]?.body)) as {
  2318. content?: string;
  2319. };
  2320. expect(interactionBody.content).toContain("Build the board");
  2321. const token = String(interactionBody.content).match(
  2322. /\/elicitation ([a-f0-9]{12}) approve/u,
  2323. )?.[1];
  2324. expect(token).toMatch(/^[a-f0-9]{12}$/u);
  2325. await service.handleProviderCallbackResponse("feishu", {
  2326. botId: "feishu-1",
  2327. event: {
  2328. operator: { operator_id: { open_id: "ou_user" } },
  2329. action: {
  2330. behaviors: [
  2331. {
  2332. type: "callback",
  2333. value: {
  2334. command: `/elicitation ${token} approve`,
  2335. zcodeCardText: "Review this implementation plan.",
  2336. },
  2337. },
  2338. ],
  2339. },
  2340. context: { card_update_token: "interaction-token" },
  2341. },
  2342. });
  2343. const retainedPlanUpdate = fetchMock.mock.calls.find(([url]) =>
  2344. String(url).includes("/open-apis/interactive/v1/card/update"),
  2345. );
  2346. expect(String(retainedPlanUpdate?.[1]?.body)).toContain("Build the board");
  2347. expect(String(retainedPlanUpdate?.[1]?.body)).not.toContain('"tag":"button"');
  2348. expect(fetchMock).toHaveBeenCalledWith(
  2349. expect.stringContaining("/open-apis/im/v1/messages/om_interaction"),
  2350. expect.objectContaining({ method: "PATCH" }),
  2351. );
  2352. expect(
  2353. fetchMock.mock.calls.some(
  2354. ([url, init]) =>
  2355. String(url).includes("/open-apis/im/v1/messages/om_interaction") &&
  2356. init?.method === "DELETE",
  2357. ),
  2358. ).toBe(false);
  2359. expect(
  2360. fetchMock.mock.calls.some(
  2361. ([url, init]) =>
  2362. String(url).includes("/open-apis/im/v1/messages/om_streaming") &&
  2363. init?.method === "DELETE",
  2364. ),
  2365. ).toBe(false);
  2366. await streamListeners[0]?.({
  2367. type: "agent_message_chunk",
  2368. taskId: "task-1",
  2369. traceId: "trace-continue",
  2370. content: "开始执行计划。",
  2371. });
  2372. expect(messagePostCount).toBe(3);
  2373. const continuedStreamPost = fetchMock.mock.calls
  2374. .filter(
  2375. ([url, init]) =>
  2376. String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id") &&
  2377. init?.method === "POST",
  2378. )
  2379. .at(-1);
  2380. expect(String(continuedStreamPost?.[1]?.body)).toContain("开始执行计划");
  2381. expect(String(continuedStreamPost?.[1]?.body)).not.toContain("Build the board");
  2382. service.disposeAll();
  2383. });
  2384. it("continues terminal stream handling after a Feishu card request times out", async () => {
  2385. vi.useFakeTimers();
  2386. const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
  2387. if (url.endsWith("/tenant_access_token/internal")) {
  2388. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2389. }
  2390. if (url.includes("/open-apis/im/v1/messages?receive_id_type=open_id")) {
  2391. return await new Promise<Response>((_resolve, reject) => {
  2392. init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
  2393. once: true,
  2394. });
  2395. });
  2396. }
  2397. return new Response(JSON.stringify({ code: 0 }));
  2398. });
  2399. vi.stubGlobal("fetch", fetchMock);
  2400. const repo = f.createMemoryRepo({
  2401. ...f.feishuConfig,
  2402. bots: [
  2403. {
  2404. ...f.feishuConfig.bots[0]!,
  2405. replyMode: "streaming_card",
  2406. },
  2407. ],
  2408. });
  2409. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2410. const service = f.createBotsService({
  2411. runStartupBackgroundTasks: false,
  2412. credentialService: f.createCredentialService({
  2413. "feishu-secret": "secret",
  2414. }),
  2415. legacyTaskService: {
  2416. ...f.createLegacyTaskService(),
  2417. onDynamicTaskEvent: vi.fn(
  2418. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2419. streamListeners.push(listener);
  2420. return { dispose() {} };
  2421. },
  2422. ),
  2423. },
  2424. repo: repo as never,
  2425. });
  2426. await service.handleInboundMessage({
  2427. botId: "feishu-1",
  2428. text: "start",
  2429. actor: feishuActor,
  2430. });
  2431. const chunkPromise = streamListeners[0]?.({
  2432. type: "agent_message_chunk",
  2433. taskId: "task-1",
  2434. traceId: "trace-timeout",
  2435. content: "working",
  2436. });
  2437. await vi.waitFor(() =>
  2438. expect(
  2439. fetchMock.mock.calls.some(([url]) =>
  2440. String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id"),
  2441. ),
  2442. ).toBe(true),
  2443. );
  2444. await vi.advanceTimersByTimeAsync(15_000);
  2445. await chunkPromise;
  2446. await vi.advanceTimersByTimeAsync(1_000);
  2447. const completePromise = streamListeners[0]?.({
  2448. type: "task_complete",
  2449. taskId: "task-1",
  2450. traceId: "trace-timeout",
  2451. stopReason: "end_turn",
  2452. });
  2453. await vi.advanceTimersByTimeAsync(1_000);
  2454. await completePromise;
  2455. expect(
  2456. fetchMock.mock.calls.filter(([url]) =>
  2457. String(url).includes("/open-apis/im/v1/messages?receive_id_type=open_id"),
  2458. ),
  2459. ).toHaveLength(1);
  2460. expect((await service.getStatus()).botRuntime[0]?.deliveryRetryId).toBeTruthy();
  2461. service.disposeAll();
  2462. vi.useRealTimers();
  2463. });
  2464. it("serializes streamed channel replies before terminal change summaries", async () => {
  2465. const deliveredTexts: string[] = [];
  2466. const contentSendStarted = createDeferred<void>();
  2467. const allowContentSend = createDeferred<void>();
  2468. const fetchMock = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
  2469. const body =
  2470. typeof init?.body === "string" ? (JSON.parse(init.body) as { text?: string }) : {};
  2471. const text = body.text ?? "";
  2472. if (text.includes("操作方式")) {
  2473. contentSendStarted.resolve(undefined);
  2474. await allowContentSend.promise;
  2475. }
  2476. deliveredTexts.push(text);
  2477. return new Response(JSON.stringify({ ok: true }), { status: 200 });
  2478. });
  2479. vi.stubGlobal("fetch", fetchMock);
  2480. const repo = f.createMemoryRepo({
  2481. ...f.baseConfig,
  2482. bots: [
  2483. {
  2484. ...f.baseConfig.bots[0]!,
  2485. webhookUrl: "https://example.test/zcode-bot-outbound",
  2486. },
  2487. ],
  2488. });
  2489. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2490. const completedTask = {
  2491. taskId: "task-1",
  2492. title: "Task 1",
  2493. workspacePath: "/tmp/workspace",
  2494. workspaceIdentity: "ssh://host/tmp/workspace",
  2495. provider: "codex",
  2496. status: "completed",
  2497. };
  2498. const legacyTaskService = {
  2499. ...f.createLegacyTaskService(),
  2500. listTasks: vi.fn(async () => [completedTask]),
  2501. getTaskSnapshot: vi.fn(async () => ({
  2502. meta: completedTask,
  2503. messages: [
  2504. {
  2505. role: "assistant" as const,
  2506. content: "操作方式",
  2507. timestamp: 1,
  2508. turnIndex: 1,
  2509. },
  2510. ],
  2511. fileChanges: [
  2512. {
  2513. turnIndex: 1,
  2514. snapshots: [
  2515. {
  2516. path: "/tmp/workspace/angry-birds.html",
  2517. beforeContent: null,
  2518. afterContent: "<html></html>\n",
  2519. writeCount: 1,
  2520. },
  2521. ],
  2522. },
  2523. ],
  2524. })),
  2525. onDynamicTaskEvent: vi.fn(
  2526. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2527. streamListeners.push(listener);
  2528. return { dispose() {} };
  2529. },
  2530. ),
  2531. };
  2532. const broadcastService = f.createBroadcastService();
  2533. const service = f.createBotsService({
  2534. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  2535. legacyTaskService,
  2536. broadcastService,
  2537. repo: repo as never,
  2538. });
  2539. await bind(service);
  2540. await service.handleInboundMessage({
  2541. botId: "webhook-1",
  2542. text: "生成游戏",
  2543. actor,
  2544. });
  2545. const contentPromise = streamListeners[0]?.({
  2546. type: "agent_message_chunk",
  2547. taskId: "task-1",
  2548. traceId: "trace-1",
  2549. content: "操作方式\n\n继续说明。",
  2550. });
  2551. const terminalPromise = streamListeners[0]?.({
  2552. type: "task_complete",
  2553. taskId: "task-1",
  2554. traceId: "trace-1",
  2555. stopReason: "end_turn",
  2556. });
  2557. await contentSendStarted.promise;
  2558. await Promise.resolve();
  2559. await Promise.resolve();
  2560. expect(deliveredTexts).toEqual([]);
  2561. allowContentSend.resolve(undefined);
  2562. await Promise.all([contentPromise, terminalPromise]);
  2563. expect(deliveredTexts[0]).toContain("操作方式");
  2564. expect(deliveredTexts[0]).toContain("继续说明。");
  2565. expect(deliveredTexts[1]).toContain("变更摘要");
  2566. service.disposeAll();
  2567. });
  2568. it("sends elicitation requests to webhook channels and responds with structured content", async () => {
  2569. const fetchMock = vi.fn(
  2570. async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
  2571. );
  2572. vi.stubGlobal("fetch", fetchMock);
  2573. const repo = f.createMemoryRepo({
  2574. ...f.baseConfig,
  2575. bots: [
  2576. {
  2577. ...f.baseConfig.bots[0]!,
  2578. webhookUrl: "https://example.test/zcode-bot-outbound",
  2579. },
  2580. ],
  2581. });
  2582. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2583. const legacyTaskService = {
  2584. ...f.createLegacyTaskService(),
  2585. onDynamicTaskEvent: vi.fn(
  2586. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2587. streamListeners.push(listener);
  2588. return { dispose() {} };
  2589. },
  2590. ),
  2591. };
  2592. const broadcastService = f.createBroadcastService();
  2593. const service = f.createBotsService({
  2594. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  2595. legacyTaskService,
  2596. broadcastService,
  2597. repo: repo as never,
  2598. });
  2599. await bind(service);
  2600. await service.handleInboundMessage({
  2601. botId: "webhook-1",
  2602. text: "启动任务",
  2603. actor,
  2604. });
  2605. const subagentOrigin = {
  2606. kind: "subagent" as const,
  2607. agentType: "general-purpose",
  2608. childSessionId: "child-session-1",
  2609. parentSessionId: "task-1",
  2610. parentToolCallId: "agent-call-1",
  2611. };
  2612. await streamListeners[0]?.({
  2613. type: "elicitation_request",
  2614. taskId: "task-1",
  2615. traceId: "trace-elicit",
  2616. requestId: "elicit-1",
  2617. origin: subagentOrigin,
  2618. message: "请选择方案",
  2619. header: "方案",
  2620. options: [{ value: "fast", label: "快速" }],
  2621. });
  2622. const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
  2623. type?: string;
  2624. elicitation?: { requestId?: string };
  2625. selection?: { action?: string; token?: string };
  2626. };
  2627. expect(body.type).toBe("zcode.bot.elicitation_request");
  2628. expect(body.elicitation?.requestId).toBe("elicit-1");
  2629. expect(body.selection?.action).toBe("elicitation.respond");
  2630. expect(body.selection?.token).toMatch(/^[a-f0-9]{12}$/u);
  2631. expect(broadcastService.send).toHaveBeenCalledWith(
  2632. expect.objectContaining({
  2633. channel: "bots:task",
  2634. payload: expect.objectContaining({
  2635. event: "elicitation_request",
  2636. taskId: "task-1",
  2637. requestId: "elicit-1",
  2638. workspaceIdentity: "ssh://host/tmp/workspace",
  2639. elicitationRequest: expect.objectContaining({
  2640. requestId: "elicit-1",
  2641. message: "请选择方案",
  2642. origin: subagentOrigin,
  2643. }),
  2644. }),
  2645. }),
  2646. );
  2647. expect((await repo.readState()).bots["webhook-1"]?.pendingElicitation).toMatchObject({
  2648. requestId: "elicit-1",
  2649. runId: "trace-elicit",
  2650. taskId: "task-1",
  2651. origin: subagentOrigin,
  2652. });
  2653. const replies = await service.handleInboundMessage({
  2654. botId: "webhook-1",
  2655. text: "",
  2656. actor,
  2657. elicitationResponse: {
  2658. requestId: "elicit-1",
  2659. action: "accept",
  2660. content: { answer: "fast" },
  2661. },
  2662. });
  2663. expect(replies[0]?.text).toContain("已提交问答响应");
  2664. expect(legacyTaskService.respondElicitation).toHaveBeenCalledWith({
  2665. taskId: "task-1",
  2666. workspacePath: "/tmp/workspace",
  2667. workspaceIdentity: "ssh://host/tmp/workspace",
  2668. runId: "trace-elicit",
  2669. requestId: "elicit-1",
  2670. action: "accept",
  2671. content: { answer: "fast" },
  2672. });
  2673. expect(broadcastService.send).toHaveBeenCalledWith(
  2674. expect.objectContaining({
  2675. channel: "bots:task",
  2676. payload: expect.objectContaining({
  2677. event: "elicitation_resolved",
  2678. taskId: "task-1",
  2679. requestId: "elicit-1",
  2680. workspaceIdentity: "ssh://host/tmp/workspace",
  2681. }),
  2682. }),
  2683. );
  2684. expect((await repo.readState()).bots["webhook-1"]?.pendingElicitation).toBeUndefined();
  2685. service.disposeAll();
  2686. });
  2687. it("collects multi-select elicitation answers through numbered callbacks", async () => {
  2688. const fetchMock = vi.fn(
  2689. async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
  2690. );
  2691. vi.stubGlobal("fetch", fetchMock);
  2692. const repo = f.createMemoryRepo({
  2693. ...f.baseConfig,
  2694. bots: [
  2695. {
  2696. ...f.baseConfig.bots[0]!,
  2697. webhookUrl: "https://example.test/zcode-bot-outbound",
  2698. },
  2699. ],
  2700. });
  2701. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2702. const legacyTaskService = {
  2703. ...f.createLegacyTaskService(),
  2704. onDynamicTaskEvent: vi.fn(
  2705. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2706. streamListeners.push(listener);
  2707. return { dispose() {} };
  2708. },
  2709. ),
  2710. };
  2711. const broadcastService = f.createBroadcastService();
  2712. const service = f.createBotsService({
  2713. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  2714. legacyTaskService,
  2715. broadcastService,
  2716. repo: repo as never,
  2717. });
  2718. await bind(service);
  2719. await service.handleInboundMessage({
  2720. botId: "webhook-1",
  2721. text: "启动任务",
  2722. actor,
  2723. });
  2724. await streamListeners[0]?.({
  2725. type: "elicitation_request",
  2726. taskId: "task-1",
  2727. traceId: "trace-elicit",
  2728. requestId: "elicit-multi",
  2729. message: "选择保障项",
  2730. options: [
  2731. { value: "tests", label: "测试" },
  2732. { value: "docs", label: "文档" },
  2733. ],
  2734. multiSelect: true,
  2735. });
  2736. const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
  2737. selection?: { token?: string };
  2738. };
  2739. const token = body.selection?.token;
  2740. expect(token).toMatch(/^[a-f0-9]{12}$/u);
  2741. const staleReplies = await service.handleInboundMessage({
  2742. botId: "webhook-1",
  2743. text: "/elicitation 1",
  2744. actor,
  2745. });
  2746. expect(staleReplies[0]?.text).toContain("问答请求已过期");
  2747. expect(legacyTaskService.respondElicitation).not.toHaveBeenCalled();
  2748. await service.handleInboundMessage({
  2749. botId: "webhook-1",
  2750. text: `/elicitation ${token} 1`,
  2751. actor,
  2752. });
  2753. expect(broadcastService.send).toHaveBeenCalledWith(
  2754. expect.objectContaining({
  2755. channel: "bots:task",
  2756. payload: expect.objectContaining({
  2757. event: "elicitation_request",
  2758. requestId: "elicit-multi",
  2759. elicitationRequest: expect.objectContaining({
  2760. currentQuestionIndex: 0,
  2761. answerDrafts: { answer_0: ["tests"] },
  2762. }),
  2763. }),
  2764. }),
  2765. );
  2766. await service.handleInboundMessage({
  2767. botId: "webhook-1",
  2768. text: `/elicitation ${token} 2`,
  2769. actor,
  2770. });
  2771. expect(broadcastService.send).toHaveBeenCalledWith(
  2772. expect.objectContaining({
  2773. channel: "bots:task",
  2774. payload: expect.objectContaining({
  2775. event: "elicitation_request",
  2776. requestId: "elicit-multi",
  2777. elicitationRequest: expect.objectContaining({
  2778. currentQuestionIndex: 0,
  2779. answerDrafts: { answer_0: ["tests", "docs"] },
  2780. }),
  2781. }),
  2782. }),
  2783. );
  2784. const doneReplies = await service.handleInboundMessage({
  2785. botId: "webhook-1",
  2786. text: `/elicitation ${token} 3`,
  2787. actor,
  2788. });
  2789. expect(doneReplies[0]?.text).toContain("已提交问答响应");
  2790. expect(legacyTaskService.respondElicitation).toHaveBeenCalledWith(
  2791. expect.objectContaining({
  2792. taskId: "task-1",
  2793. runId: "trace-elicit",
  2794. requestId: "elicit-multi",
  2795. content: {
  2796. answers: { 选择保障项: "tests, docs" },
  2797. answer_0: ["tests", "docs"],
  2798. answer: ["tests", "docs"],
  2799. },
  2800. }),
  2801. );
  2802. service.disposeAll();
  2803. });
  2804. it("replaces the Feishu interaction card when custom answer input is expanded", async () => {
  2805. let messagePostCount = 0;
  2806. const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
  2807. if (url.endsWith("/tenant_access_token/internal")) {
  2808. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  2809. }
  2810. if (url.includes("/open-apis/im/v1/messages?receive_id_type=") && init?.method === "POST") {
  2811. messagePostCount += 1;
  2812. return new Response(
  2813. JSON.stringify({ code: 0, data: { message_id: `om_question_${messagePostCount}` } }),
  2814. );
  2815. }
  2816. if (url.includes("/open-apis/interactive/v1/card/update")) {
  2817. return new Response(JSON.stringify({ code: 0 }));
  2818. }
  2819. return new Response(JSON.stringify({ code: 0 }));
  2820. });
  2821. vi.stubGlobal("fetch", fetchMock);
  2822. const repo = f.createMemoryRepo(f.feishuConfig, {
  2823. version: 3,
  2824. bots: {
  2825. "feishu-1": {
  2826. botId: "feishu-1",
  2827. workspacePath: "/tmp/workspace",
  2828. workspaceIdentity: "ssh://host/tmp/workspace",
  2829. workspaceId: "ssh://host/tmp/workspace",
  2830. mode: "task",
  2831. activeTaskId: "task-1",
  2832. updatedAt: Date.now(),
  2833. },
  2834. },
  2835. });
  2836. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  2837. const legacyTaskService = {
  2838. ...f.createLegacyTaskService(),
  2839. onDynamicTaskEvent: vi.fn(
  2840. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  2841. streamListeners.push(listener);
  2842. return { dispose() {} };
  2843. },
  2844. ),
  2845. };
  2846. const service = f.createBotsService({
  2847. credentialService: f.createCredentialService({
  2848. "feishu-secret": "secret",
  2849. }),
  2850. legacyTaskService,
  2851. repo: repo as never,
  2852. });
  2853. await service.handleInboundMessage({
  2854. botId: "feishu-1",
  2855. text: "启动任务",
  2856. actor: feishuActor,
  2857. });
  2858. await streamListeners[0]?.({
  2859. type: "elicitation_request",
  2860. taskId: "task-1",
  2861. traceId: "trace-elicit",
  2862. requestId: "elicit-feishu",
  2863. message: "你希望游戏有什么功能?",
  2864. options: [
  2865. { value: "base", label: "基础玩法" },
  2866. { value: "score", label: "分数系统" },
  2867. ],
  2868. multiSelect: true,
  2869. });
  2870. const initialSendCount = fetchMock.mock.calls.filter(([url]) =>
  2871. String(url).includes("/open-apis/im/v1/messages?receive_id_type="),
  2872. ).length;
  2873. const firstCardCall = fetchMock.mock.calls.find(([url]) =>
  2874. String(url).includes("/open-apis/im/v1/messages"),
  2875. );
  2876. const firstCardBody = JSON.parse(String(firstCardCall?.[1]?.body)) as {
  2877. content?: string;
  2878. };
  2879. const token = String(firstCardBody.content).match(
  2880. /\/elicitation ([a-f0-9]{12}) __form__:/u,
  2881. )?.[1];
  2882. expect(token).toMatch(/^[a-f0-9]{12}$/u);
  2883. const toggleResponse = await service.handleProviderCallbackResponse("feishu", {
  2884. botId: "feishu-1",
  2885. event: {
  2886. operator: { operator_id: { open_id: "ou_user" } },
  2887. action: {
  2888. behaviors: [
  2889. {
  2890. type: "callback",
  2891. value: {
  2892. command: `/elicitation ${token} base`,
  2893. zcodeCardText: "Question",
  2894. },
  2895. },
  2896. ],
  2897. },
  2898. context: { card_update_token: "ask-card-token-toggle" },
  2899. },
  2900. });
  2901. expect(toggleResponse.ok).toBe(true);
  2902. expect(toggleResponse.replies[0]?.elicitation).toMatchObject({
  2903. requestId: "elicit-feishu",
  2904. status: "pending",
  2905. answers: { "0": ["base"] },
  2906. });
  2907. const customResponse = await service.handleProviderCallbackResponse("feishu", {
  2908. botId: "feishu-1",
  2909. event: {
  2910. operator: { operator_id: { open_id: "ou_user" } },
  2911. action: {
  2912. behaviors: [
  2913. {
  2914. type: "callback",
  2915. value: {
  2916. command: `/elicitation ${token} __custom__`,
  2917. zcodeCardText: "Question",
  2918. },
  2919. },
  2920. ],
  2921. },
  2922. context: { card_update_token: "ask-card-token-custom" },
  2923. },
  2924. });
  2925. expect(customResponse.ok).toBe(true);
  2926. expect(customResponse.replies[0]?.elicitation).toMatchObject({
  2927. requestId: "elicit-feishu",
  2928. status: "pending",
  2929. answers: { "0": ["base"] },
  2930. expandedCustomAnswerQuestionIndexes: [0],
  2931. });
  2932. const customFormUpdate = fetchMock.mock.calls
  2933. .filter(([url]) => String(url).includes("/open-apis/interactive/v1/card/update"))
  2934. .at(-1);
  2935. const customFormBody = JSON.parse(String(customFormUpdate?.[1]?.body)) as { card?: unknown };
  2936. expect(JSON.stringify(customFormBody.card)).toContain('"tag":"form"');
  2937. expect(JSON.stringify(customFormBody.card)).toContain('"tag":"input"');
  2938. const response = await service.handleProviderCallbackResponse("feishu", {
  2939. botId: "feishu-1",
  2940. event: {
  2941. operator: { operator_id: { open_id: "ou_user" } },
  2942. action: {
  2943. behaviors: [
  2944. {
  2945. type: "callback",
  2946. value: {
  2947. command: `/elicitation ${token} __form__:`,
  2948. zcodeCardText: "Question",
  2949. },
  2950. },
  2951. ],
  2952. form_value: { answer: "排行榜" },
  2953. },
  2954. context: { card_update_token: "ask-card-token" },
  2955. },
  2956. });
  2957. expect(response.ok).toBe(true);
  2958. expect(response.replies[0]?.elicitation).toMatchObject({
  2959. requestId: "elicit-feishu",
  2960. status: "completed",
  2961. });
  2962. expect(
  2963. fetchMock.mock.calls.filter(
  2964. ([url, init]) =>
  2965. String(url).includes("/open-apis/im/v1/messages?receive_id_type=") &&
  2966. init?.method === "POST",
  2967. ),
  2968. ).toHaveLength(initialSendCount);
  2969. const deleteCalls = fetchMock.mock.calls.filter(
  2970. ([url, init]) =>
  2971. String(url).includes("/open-apis/im/v1/messages/om_question_") && init?.method === "DELETE",
  2972. );
  2973. expect(deleteCalls).toHaveLength(0);
  2974. expect(
  2975. fetchMock.mock.calls.filter(([url]) =>
  2976. String(url).includes("/open-apis/interactive/v1/card/update"),
  2977. ),
  2978. ).toHaveLength(3);
  2979. expect(
  2980. fetchMock.mock.calls.filter(
  2981. ([url, init]) =>
  2982. String(url).includes("/open-apis/im/v1/messages/om_question_") &&
  2983. init?.method === "PATCH",
  2984. ),
  2985. ).toHaveLength(3);
  2986. expect(legacyTaskService.respondElicitation).toHaveBeenCalledWith(
  2987. expect.objectContaining({
  2988. taskId: "task-1",
  2989. runId: "trace-elicit",
  2990. requestId: "elicit-feishu",
  2991. content: {
  2992. answers: { "你希望游戏有什么功能?": "base, 排行榜" },
  2993. answer_0: ["base", "排行榜"],
  2994. answer: ["base", "排行榜"],
  2995. },
  2996. }),
  2997. );
  2998. service.disposeAll();
  2999. });
  3000. it("sends the next Feishu question after the answered card is acknowledged", async () => {
  3001. let messagePostCount = 0;
  3002. const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
  3003. if (url.endsWith("/tenant_access_token/internal")) {
  3004. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3005. }
  3006. if (url.includes("/open-apis/interactive/v1/card/update")) {
  3007. return new Response(JSON.stringify({ code: 0 }));
  3008. }
  3009. if (url.includes("/open-apis/im/v1/messages?receive_id_type=") && init?.method === "POST") {
  3010. messagePostCount += 1;
  3011. return new Response(
  3012. JSON.stringify({ code: 0, data: { message_id: `om_question_${messagePostCount}` } }),
  3013. );
  3014. }
  3015. return new Response(JSON.stringify({ code: 0 }));
  3016. });
  3017. vi.stubGlobal("fetch", fetchMock);
  3018. const repo = f.createMemoryRepo(f.feishuConfig, {
  3019. version: 3,
  3020. bots: {
  3021. "feishu-1": {
  3022. botId: "feishu-1",
  3023. workspacePath: "/tmp/workspace",
  3024. workspaceIdentity: "ssh://host/tmp/workspace",
  3025. workspaceId: "ssh://host/tmp/workspace",
  3026. mode: "task",
  3027. activeTaskId: "task-1",
  3028. updatedAt: Date.now(),
  3029. },
  3030. },
  3031. });
  3032. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  3033. const legacyTaskService = {
  3034. ...f.createLegacyTaskService(),
  3035. onDynamicTaskEvent: vi.fn(
  3036. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  3037. streamListeners.push(listener);
  3038. return { dispose() {} };
  3039. },
  3040. ),
  3041. };
  3042. const broadcastService = f.createBroadcastService();
  3043. const service = f.createBotsService({
  3044. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  3045. legacyTaskService,
  3046. broadcastService,
  3047. repo: repo as never,
  3048. });
  3049. await service.handleInboundMessage({
  3050. botId: "feishu-1",
  3051. text: "启动任务",
  3052. actor: feishuActor,
  3053. });
  3054. await streamListeners[0]?.({
  3055. type: "elicitation_request",
  3056. taskId: "task-1",
  3057. traceId: "trace-elicit-two",
  3058. requestId: "elicit-feishu-two",
  3059. message: "选择技术方案",
  3060. options: [{ value: "web", label: "纯前端" }],
  3061. questions: [
  3062. {
  3063. question: "选择技术方案",
  3064. header: "技术方案",
  3065. options: [{ value: "web", label: "纯前端" }],
  3066. },
  3067. {
  3068. question: "选择棋盘尺寸",
  3069. header: "棋盘",
  3070. options: [{ value: "15", label: "15 × 15" }],
  3071. },
  3072. ],
  3073. });
  3074. const firstCardCall = fetchMock.mock.calls.find(([url]) =>
  3075. String(url).includes("/open-apis/im/v1/messages"),
  3076. );
  3077. const firstCardBody = JSON.parse(String(firstCardCall?.[1]?.body)) as {
  3078. content?: string;
  3079. };
  3080. const token = String(firstCardBody.content).match(/\/elicitation ([a-f0-9]{12}) web/u)?.[1];
  3081. expect(token).toMatch(/^[a-f0-9]{12}$/u);
  3082. const response = await service.handleProviderCallbackResponse("feishu", {
  3083. botId: "feishu-1",
  3084. event: {
  3085. operator: { operator_id: { open_id: "ou_user" } },
  3086. action: {
  3087. behaviors: [
  3088. {
  3089. type: "callback",
  3090. value: {
  3091. command: `/elicitation ${token} web`,
  3092. zcodeCardText: "Question",
  3093. },
  3094. },
  3095. ],
  3096. },
  3097. context: { card_update_token: "ask-next-card-token" },
  3098. },
  3099. });
  3100. expect(response.ok).toBe(true);
  3101. expect(response.replies[0]?.elicitation).toMatchObject({
  3102. requestId: "elicit-feishu-two",
  3103. currentQuestionIndex: 1,
  3104. status: "pending",
  3105. answers: { "0": ["web"] },
  3106. });
  3107. const messageCalls = fetchMock.mock.calls.filter(
  3108. ([url, init]) =>
  3109. String(url).includes("/open-apis/im/v1/messages?receive_id_type=") &&
  3110. init?.method === "POST",
  3111. );
  3112. expect(messageCalls).toHaveLength(1);
  3113. const updateCall = fetchMock.mock.calls.find(([url]) =>
  3114. String(url).includes("/open-apis/interactive/v1/card/update"),
  3115. );
  3116. const updateBody = JSON.parse(String(updateCall?.[1]?.body)) as { card?: unknown };
  3117. expect(JSON.stringify(updateBody.card)).toContain("2/2");
  3118. expect(JSON.stringify(updateBody.card)).toContain("选择棋盘尺寸");
  3119. const updatedCardJson = JSON.stringify(updateBody.card);
  3120. expect(updatedCardJson).toContain("选择技术方案");
  3121. expect(updatedCardJson).toContain("纯前端");
  3122. expect(updatedCardJson.indexOf("选择技术方案")).toBeLessThan(
  3123. updatedCardJson.indexOf('"tag":"hr"'),
  3124. );
  3125. expect(updatedCardJson.indexOf('"tag":"hr"')).toBeLessThan(
  3126. updatedCardJson.indexOf("选择棋盘尺寸"),
  3127. );
  3128. expect(fetchMock.mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(false);
  3129. expect(fetchMock).toHaveBeenCalledWith(
  3130. expect.stringContaining("/open-apis/im/v1/messages/om_question_1"),
  3131. expect.objectContaining({ method: "PATCH" }),
  3132. );
  3133. expect(legacyTaskService.respondElicitation).not.toHaveBeenCalled();
  3134. service.disposeAll();
  3135. });
  3136. it("submits Feishu single-select AskUserQuestion preset answers immediately", async () => {
  3137. const fetchMock = vi.fn(async (url: string) => {
  3138. if (url.endsWith("/tenant_access_token/internal")) {
  3139. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  3140. }
  3141. if (url.includes("/open-apis/im/v1/messages")) {
  3142. return new Response(JSON.stringify({ code: 0, data: { message_id: "om_question" } }));
  3143. }
  3144. if (url.includes("/open-apis/interactive/v1/card/update")) {
  3145. return new Response(JSON.stringify({ code: 0 }));
  3146. }
  3147. return new Response(JSON.stringify({ code: 0 }));
  3148. });
  3149. vi.stubGlobal("fetch", fetchMock);
  3150. const repo = f.createMemoryRepo(f.feishuConfig, {
  3151. version: 3,
  3152. bots: {
  3153. "feishu-1": {
  3154. botId: "feishu-1",
  3155. workspacePath: "/tmp/workspace",
  3156. workspaceIdentity: "ssh://host/tmp/workspace",
  3157. workspaceId: "ssh://host/tmp/workspace",
  3158. mode: "task",
  3159. activeTaskId: "task-1",
  3160. updatedAt: Date.now(),
  3161. },
  3162. },
  3163. });
  3164. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  3165. const legacyTaskService = {
  3166. ...f.createLegacyTaskService(),
  3167. onDynamicTaskEvent: vi.fn(
  3168. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  3169. streamListeners.push(listener);
  3170. return { dispose() {} };
  3171. },
  3172. ),
  3173. };
  3174. const service = f.createBotsService({
  3175. credentialService: f.createCredentialService({
  3176. "feishu-secret": "secret",
  3177. }),
  3178. legacyTaskService,
  3179. repo: repo as never,
  3180. });
  3181. await service.handleInboundMessage({
  3182. botId: "feishu-1",
  3183. text: "启动任务",
  3184. actor: feishuActor,
  3185. });
  3186. await streamListeners[0]?.({
  3187. type: "elicitation_request",
  3188. taskId: "task-1",
  3189. traceId: "trace-elicit-single",
  3190. requestId: "elicit-feishu-single",
  3191. message: "你想在哪里运行贪吃蛇游戏?",
  3192. options: [{ value: "web", label: "网页版 (HTML/CSS/JS)" }],
  3193. });
  3194. const firstCardCall = fetchMock.mock.calls.find(([url]) =>
  3195. String(url).includes("/open-apis/im/v1/messages"),
  3196. );
  3197. const firstCardBody = JSON.parse(String(firstCardCall?.[1]?.body)) as {
  3198. content?: string;
  3199. };
  3200. const token = String(firstCardBody.content).match(/\/elicitation ([a-f0-9]{12}) web/u)?.[1];
  3201. expect(token).toMatch(/^[a-f0-9]{12}$/u);
  3202. const response = await service.handleProviderCallbackResponse("feishu", {
  3203. botId: "feishu-1",
  3204. event: {
  3205. operator: { operator_id: { open_id: "ou_user" } },
  3206. action: {
  3207. behaviors: [
  3208. {
  3209. type: "callback",
  3210. value: {
  3211. command: `/elicitation ${token} web`,
  3212. zcodeCardText: "Question",
  3213. },
  3214. },
  3215. ],
  3216. },
  3217. context: { card_update_token: "ask-single-card-token" },
  3218. },
  3219. });
  3220. expect(response.ok).toBe(true);
  3221. expect(response.replies[0]?.elicitation).toMatchObject({
  3222. requestId: "elicit-feishu-single",
  3223. status: "completed",
  3224. });
  3225. expect(legacyTaskService.respondElicitation).toHaveBeenCalledWith(
  3226. expect.objectContaining({
  3227. taskId: "task-1",
  3228. runId: "trace-elicit-single",
  3229. requestId: "elicit-feishu-single",
  3230. content: {
  3231. answers: { "你想在哪里运行贪吃蛇游戏?": "web" },
  3232. answer_0: "web",
  3233. answer: "web",
  3234. },
  3235. }),
  3236. );
  3237. const deleteCalls = fetchMock.mock.calls.filter(
  3238. ([url, init]) =>
  3239. String(url).includes("/open-apis/im/v1/messages/om_question") && init?.method === "DELETE",
  3240. );
  3241. expect(deleteCalls).toHaveLength(0);
  3242. expect(
  3243. fetchMock.mock.calls.filter(([url]) =>
  3244. String(url).includes("/open-apis/interactive/v1/card/update"),
  3245. ),
  3246. ).toHaveLength(1);
  3247. service.disposeAll();
  3248. });
  3249. it("serializes concurrent elicitation replies for the same actor", async () => {
  3250. const fetchMock = vi.fn(
  3251. async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
  3252. );
  3253. vi.stubGlobal("fetch", fetchMock);
  3254. const repo = f.createMemoryRepo({
  3255. ...f.baseConfig,
  3256. bots: [
  3257. {
  3258. ...f.baseConfig.bots[0]!,
  3259. webhookUrl: "https://example.test/zcode-bot-outbound",
  3260. },
  3261. ],
  3262. });
  3263. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  3264. const deferredRespond = createDeferred<boolean>();
  3265. const legacyTaskService = {
  3266. ...f.createLegacyTaskService(),
  3267. respondElicitation: vi.fn(() => deferredRespond.promise),
  3268. onDynamicTaskEvent: vi.fn(
  3269. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  3270. streamListeners.push(listener);
  3271. return { dispose() {} };
  3272. },
  3273. ),
  3274. };
  3275. const service = f.createBotsService({
  3276. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3277. legacyTaskService,
  3278. repo: repo as never,
  3279. });
  3280. await bind(service);
  3281. await service.handleInboundMessage({
  3282. botId: "webhook-1",
  3283. text: "启动任务",
  3284. actor,
  3285. });
  3286. await streamListeners[0]?.({
  3287. type: "elicitation_request",
  3288. taskId: "task-1",
  3289. traceId: "trace-elicit",
  3290. requestId: "elicit-concurrent",
  3291. message: "选择方案",
  3292. options: [{ value: "fast", label: "快速" }],
  3293. });
  3294. const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
  3295. selection?: { token?: string };
  3296. };
  3297. const token = body.selection?.token;
  3298. expect(token).toMatch(/^[a-f0-9]{12}$/u);
  3299. const firstReply = service.handleInboundMessage({
  3300. botId: "webhook-1",
  3301. text: `/elicitation ${token} 1`,
  3302. actor: { ...actor, providerMessageId: "reply-1" },
  3303. });
  3304. const secondReply = service.handleInboundMessage({
  3305. botId: "webhook-1",
  3306. text: `/elicitation ${token} 1`,
  3307. actor: { ...actor, providerMessageId: "reply-2" },
  3308. });
  3309. await vi.waitFor(() => {
  3310. expect(legacyTaskService.respondElicitation).toHaveBeenCalledTimes(1);
  3311. });
  3312. deferredRespond.resolve(true);
  3313. const [firstReplies, secondReplies] = await Promise.all([firstReply, secondReply]);
  3314. expect(firstReplies[0]?.text).toContain("已提交问答响应");
  3315. expect(secondReplies[0]?.text).toContain("问答请求已过期");
  3316. expect(legacyTaskService.respondElicitation).toHaveBeenCalledTimes(1);
  3317. service.disposeAll();
  3318. });
  3319. it("keeps an elicitation retryable when the v4 interaction ACK fails", async () => {
  3320. const repo = f.createMemoryRepo(f.weixinConfig, {
  3321. version: 3,
  3322. bots: {
  3323. "weixin-1": {
  3324. botId: "weixin-1",
  3325. workspacePath: "/tmp/workspace",
  3326. workspaceId: "/tmp/workspace",
  3327. mode: "task",
  3328. activeTaskId: "task-1",
  3329. pendingElicitation: {
  3330. taskId: "task-1",
  3331. requestId: "elicit-retry",
  3332. runId: "trace-retry",
  3333. currentQuestionIndex: 0,
  3334. questions: [
  3335. {
  3336. question: "是否继续?",
  3337. header: "确认",
  3338. options: [{ value: "yes", label: "继续" }],
  3339. },
  3340. ],
  3341. answers: {},
  3342. },
  3343. updatedAt: Date.now(),
  3344. },
  3345. },
  3346. });
  3347. const legacyTaskService = f.createLegacyTaskService();
  3348. vi.mocked(legacyTaskService.respondElicitation)
  3349. .mockRejectedValueOnce(new Error("temporary v4 failure"))
  3350. .mockResolvedValueOnce(true);
  3351. const service = f.createBotsService({
  3352. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  3353. legacyTaskService,
  3354. repo: repo as never,
  3355. });
  3356. await expect(
  3357. service.handleInboundMessage({
  3358. botId: "weixin-1",
  3359. text: "继续",
  3360. actor: weixinActor,
  3361. }),
  3362. ).rejects.toThrow("temporary v4 failure");
  3363. const pendingAfterFailure = (await repo.readState()).bots["weixin-1"]?.pendingElicitation;
  3364. expect(pendingAfterFailure).toMatchObject({ requestId: "elicit-retry" });
  3365. expect(pendingAfterFailure?.handledAt).toBeUndefined();
  3366. const retry = await service.handleInboundMessage({
  3367. botId: "weixin-1",
  3368. text: "继续",
  3369. actor: weixinActor,
  3370. });
  3371. expect(retry[0]?.text).toContain("已提交问答响应");
  3372. expect(legacyTaskService.respondElicitation).toHaveBeenCalledTimes(2);
  3373. service.disposeAll();
  3374. });
  3375. it("keeps a permission retryable when the v4 interaction ACK fails", async () => {
  3376. const repo = f.createMemoryRepo(f.telegramConfig, {
  3377. version: 3,
  3378. bots: {
  3379. "telegram-1": {
  3380. botId: "telegram-1",
  3381. workspacePath: "/tmp/workspace",
  3382. workspaceId: "/tmp/workspace",
  3383. mode: "task",
  3384. activeTaskId: "task-1",
  3385. pendingPermissionOptions: [
  3386. {
  3387. requestId: "permission-retry",
  3388. optionId: "allow_once",
  3389. command: "approve",
  3390. label: "允许",
  3391. response: { decision: "allow", reason: "Approved by bot" },
  3392. },
  3393. ],
  3394. updatedAt: Date.now(),
  3395. },
  3396. },
  3397. });
  3398. const legacyTaskService = f.createLegacyTaskService();
  3399. vi.mocked(legacyTaskService.respondPermission)
  3400. .mockRejectedValueOnce(new Error("temporary permission failure"))
  3401. .mockResolvedValueOnce(true);
  3402. const service = f.createBotsService({
  3403. credentialService: f.createCredentialService({ "telegram-token": "token" }),
  3404. legacyTaskService,
  3405. repo: repo as never,
  3406. });
  3407. const telegramActor = {
  3408. provider: "telegram" as const,
  3409. botId: "telegram-1",
  3410. providerUserId: "user-1",
  3411. chatType: "private" as const,
  3412. };
  3413. await expect(
  3414. service.handleInboundMessage({
  3415. botId: "telegram-1",
  3416. text: "/permission 1",
  3417. actor: telegramActor,
  3418. }),
  3419. ).rejects.toThrow("temporary permission failure");
  3420. const permissionAfterFailure = (await repo.readState()).bots["telegram-1"]
  3421. ?.pendingPermissionOptions?.[0];
  3422. expect(permissionAfterFailure?.handledAt).toBeUndefined();
  3423. const retry = await service.handleInboundMessage({
  3424. botId: "telegram-1",
  3425. text: "/permission 1",
  3426. actor: telegramActor,
  3427. });
  3428. expect(retry[0]?.text).toContain("已提交权限响应");
  3429. expect(legacyTaskService.respondPermission).toHaveBeenCalledTimes(2);
  3430. service.disposeAll();
  3431. });
  3432. it("returns ok=false and skips provider ACK when callback business handling fails", async () => {
  3433. const repo = f.createMemoryRepo(f.telegramConfig, {
  3434. version: 3,
  3435. bots: {
  3436. "telegram-1": {
  3437. botId: "telegram-1",
  3438. workspacePath: "/tmp/workspace",
  3439. workspaceId: "/tmp/workspace",
  3440. mode: "task",
  3441. activeTaskId: "task-1",
  3442. pendingPermissionOptions: [
  3443. {
  3444. requestId: "permission-provider-retry",
  3445. optionId: "allow_once",
  3446. command: "approve",
  3447. label: "允许",
  3448. response: { decision: "allow", reason: "Approved by bot" },
  3449. },
  3450. ],
  3451. updatedAt: Date.now(),
  3452. },
  3453. },
  3454. });
  3455. const legacyTaskService = f.createLegacyTaskService();
  3456. vi.mocked(legacyTaskService.respondPermission).mockRejectedValue(
  3457. new Error("temporary permission failure"),
  3458. );
  3459. const fetchMock = vi.fn(
  3460. async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
  3461. );
  3462. vi.stubGlobal("fetch", fetchMock);
  3463. const service = f.createBotsService({
  3464. credentialService: f.createCredentialService({
  3465. "telegram-token": "token",
  3466. }),
  3467. legacyTaskService,
  3468. repo: repo as never,
  3469. });
  3470. const response = await service.handleProviderCallbackResponse("telegram", {
  3471. botId: "telegram-1",
  3472. update: {
  3473. callback_query: {
  3474. id: "callback-provider-retry",
  3475. data: "zc:permission:1",
  3476. from: { id: "user-1", username: "user" },
  3477. message: {
  3478. chat: { id: "user-1", type: "private" },
  3479. message_id: 7,
  3480. },
  3481. },
  3482. },
  3483. });
  3484. expect(response).toMatchObject({ ok: false, status: 503 });
  3485. expect(
  3486. (await repo.readState()).bots["telegram-1"]?.pendingPermissionOptions?.[0]?.handledAt,
  3487. ).toBeUndefined();
  3488. expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/answerCallbackQuery"))).toBe(
  3489. false,
  3490. );
  3491. expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/sendMessage"))).toBe(true);
  3492. service.disposeAll();
  3493. });
  3494. it("maps comma-separated elicitation text numbers to option values", async () => {
  3495. const repo = f.createMemoryRepo(f.weixinConfig, {
  3496. version: 3,
  3497. bots: {
  3498. "weixin-1": {
  3499. botId: "weixin-1",
  3500. workspacePath: "/tmp/workspace",
  3501. workspaceIdentity: "ssh://host/tmp/workspace",
  3502. workspaceId: "ssh://host/tmp/workspace",
  3503. mode: "task",
  3504. activeTaskId: "task-1",
  3505. pendingElicitation: {
  3506. taskId: "task-1",
  3507. requestId: "elicit-text",
  3508. runId: "trace-text",
  3509. currentQuestionIndex: 0,
  3510. questions: [
  3511. {
  3512. question: "选择保障项",
  3513. header: "选择保障项",
  3514. multiSelect: true,
  3515. options: [
  3516. { value: "tests", label: "测试" },
  3517. { value: "docs", label: "文档" },
  3518. ],
  3519. },
  3520. ],
  3521. answers: {},
  3522. },
  3523. updatedAt: Date.now(),
  3524. },
  3525. },
  3526. });
  3527. const legacyTaskService = f.createLegacyTaskService();
  3528. const service = f.createBotsService({
  3529. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  3530. legacyTaskService,
  3531. repo: repo as never,
  3532. });
  3533. const replies = await service.handleInboundMessage({
  3534. botId: "weixin-1",
  3535. text: "1,2",
  3536. actor: weixinActor,
  3537. });
  3538. expect(replies[0]?.text).toContain("已提交问答响应");
  3539. expect(legacyTaskService.respondElicitation).toHaveBeenCalledWith(
  3540. expect.objectContaining({
  3541. requestId: "elicit-text",
  3542. runId: "trace-text",
  3543. workspaceIdentity: "ssh://host/tmp/workspace",
  3544. content: expect.objectContaining({
  3545. answer_0: ["tests", "docs"],
  3546. answer: ["tests", "docs"],
  3547. }),
  3548. }),
  3549. );
  3550. service.disposeAll();
  3551. });
  3552. it("allows skipping a single-select question before submitting a partial answer", async () => {
  3553. const repo = f.createMemoryRepo(f.weixinConfig, {
  3554. version: 3,
  3555. bots: {
  3556. "weixin-1": {
  3557. botId: "weixin-1",
  3558. workspacePath: "/tmp/workspace",
  3559. workspaceIdentity: "ssh://host/tmp/workspace",
  3560. workspaceId: "ssh://host/tmp/workspace",
  3561. mode: "task",
  3562. activeTaskId: "task-1",
  3563. pendingElicitation: {
  3564. taskId: "task-1",
  3565. requestId: "elicit-partial",
  3566. runId: "trace-partial",
  3567. currentQuestionIndex: 0,
  3568. questions: [
  3569. {
  3570. question: "选择方案",
  3571. header: "方案",
  3572. options: [
  3573. { value: "fast", label: "快速" },
  3574. { value: "safe", label: "稳妥" },
  3575. ],
  3576. },
  3577. {
  3578. question: "选择保障项",
  3579. header: "保障项",
  3580. options: [
  3581. { value: "tests", label: "测试" },
  3582. { value: "docs", label: "文档" },
  3583. ],
  3584. },
  3585. ],
  3586. answers: {},
  3587. },
  3588. updatedAt: Date.now(),
  3589. },
  3590. },
  3591. });
  3592. const legacyTaskService = f.createLegacyTaskService();
  3593. const service = f.createBotsService({
  3594. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  3595. legacyTaskService,
  3596. repo: repo as never,
  3597. });
  3598. const promptReplies = await service.handleInboundMessage({
  3599. botId: "weixin-1",
  3600. text: "",
  3601. actor: weixinActor,
  3602. });
  3603. expect(promptReplies[0]?.text).toContain("3. 跳过");
  3604. const skipReplies = await service.handleInboundMessage({
  3605. botId: "weixin-1",
  3606. text: "3",
  3607. actor: weixinActor,
  3608. });
  3609. expect(skipReplies[0]?.text).toContain("选择保障项");
  3610. expect((await repo.readState()).bots["weixin-1"]?.pendingElicitation).toMatchObject({
  3611. currentQuestionIndex: 1,
  3612. answers: {},
  3613. });
  3614. const replies = await service.handleInboundMessage({
  3615. botId: "weixin-1",
  3616. text: "1",
  3617. actor: weixinActor,
  3618. });
  3619. expect(replies[0]?.text).toContain("已提交问答响应");
  3620. expect(legacyTaskService.respondElicitation).toHaveBeenCalledWith(
  3621. expect.objectContaining({
  3622. requestId: "elicit-partial",
  3623. content: {
  3624. answers: { 选择保障项: "tests" },
  3625. answer_1: "tests",
  3626. },
  3627. }),
  3628. );
  3629. service.disposeAll();
  3630. });
  3631. it("submits zero answers when the final bot single-select question is skipped", async () => {
  3632. const repo = f.createMemoryRepo(f.weixinConfig, {
  3633. version: 3,
  3634. bots: {
  3635. "weixin-1": {
  3636. botId: "weixin-1",
  3637. workspacePath: "/tmp/workspace",
  3638. workspaceIdentity: "ssh://host/tmp/workspace",
  3639. workspaceId: "ssh://host/tmp/workspace",
  3640. mode: "task",
  3641. activeTaskId: "task-1",
  3642. pendingElicitation: {
  3643. taskId: "task-1",
  3644. requestId: "elicit-empty",
  3645. runId: "trace-empty",
  3646. currentQuestionIndex: 0,
  3647. questions: [
  3648. {
  3649. question: "选择方案",
  3650. header: "方案",
  3651. options: [
  3652. { value: "fast", label: "快速" },
  3653. { value: "safe", label: "稳妥" },
  3654. ],
  3655. },
  3656. ],
  3657. answers: {},
  3658. },
  3659. updatedAt: Date.now(),
  3660. },
  3661. },
  3662. });
  3663. const legacyTaskService = f.createLegacyTaskService();
  3664. const service = f.createBotsService({
  3665. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  3666. legacyTaskService,
  3667. repo: repo as never,
  3668. });
  3669. const replies = await service.handleInboundMessage({
  3670. botId: "weixin-1",
  3671. text: "3",
  3672. actor: weixinActor,
  3673. });
  3674. expect(replies[0]?.text).toContain("已提交问答响应");
  3675. expect(legacyTaskService.respondElicitation).toHaveBeenCalledWith(
  3676. expect.objectContaining({
  3677. requestId: "elicit-empty",
  3678. content: { answers: {} },
  3679. }),
  3680. );
  3681. service.disposeAll();
  3682. });
  3683. it("preserves skip-like option labels and custom text as bot answers", async () => {
  3684. const repo = f.createMemoryRepo(f.weixinConfig, {
  3685. version: 3,
  3686. bots: {
  3687. "weixin-1": {
  3688. botId: "weixin-1",
  3689. workspacePath: "/tmp/workspace",
  3690. workspaceIdentity: "ssh://host/tmp/workspace",
  3691. workspaceId: "ssh://host/tmp/workspace",
  3692. mode: "task",
  3693. activeTaskId: "task-1",
  3694. pendingElicitation: {
  3695. taskId: "task-1",
  3696. requestId: "elicit-skip-labels",
  3697. runId: "trace-skip-labels",
  3698. currentQuestionIndex: 0,
  3699. questions: [
  3700. {
  3701. question: "选择按钮文案",
  3702. header: "文案",
  3703. multiSelect: true,
  3704. options: [
  3705. { value: "Skip", label: "Skip" },
  3706. { value: "下一题", label: "下一题" },
  3707. { value: "__skip__", label: "__skip__" },
  3708. { value: "Keep", label: "Keep" },
  3709. ],
  3710. },
  3711. ],
  3712. answers: {},
  3713. },
  3714. updatedAt: Date.now(),
  3715. },
  3716. },
  3717. });
  3718. const legacyTaskService = f.createLegacyTaskService();
  3719. const service = f.createBotsService({
  3720. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  3721. legacyTaskService,
  3722. repo: repo as never,
  3723. });
  3724. await service.handleInboundMessage({
  3725. botId: "weixin-1",
  3726. text: "Skip,下一题,__skip__,next",
  3727. actor: weixinActor,
  3728. });
  3729. expect(legacyTaskService.respondElicitation).toHaveBeenCalledWith(
  3730. expect.objectContaining({
  3731. requestId: "elicit-skip-labels",
  3732. content: expect.objectContaining({
  3733. answer_0: ["Skip", "下一题", "__skip__", "next"],
  3734. }),
  3735. }),
  3736. );
  3737. service.disposeAll();
  3738. });
  3739. it("creates a task from an attachment-only bot message with the default prompt", async () => {
  3740. vi.stubEnv("ZCODE_DATA_BASE_DIR", `/tmp/zcode-bot-attachments-${Date.now()}`);
  3741. const repo = f.createMemoryRepo(f.baseConfig);
  3742. const legacyTaskService = f.createLegacyTaskService();
  3743. const service = f.createBotsService({
  3744. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3745. legacyTaskService,
  3746. repo: repo as never,
  3747. });
  3748. await bind(service);
  3749. const replies = await service.handleInboundMessage({
  3750. botId: "webhook-1",
  3751. text: "",
  3752. attachments: [
  3753. {
  3754. id: "img-1",
  3755. kind: "image",
  3756. filename: "demo.png",
  3757. mimeType: "image/png",
  3758. dataBase64: "AQID",
  3759. },
  3760. ],
  3761. actor,
  3762. });
  3763. expect(replies).toEqual([]);
  3764. expect(legacyTaskService.sendPrompt).toHaveBeenCalledWith(
  3765. expect.objectContaining({
  3766. content: expect.stringContaining(
  3767. "请查看附件并根据内容协助我。\n\n附件:demo.png (image/png, 3B),已作为图片输入提供,并保存到:",
  3768. ),
  3769. attachments: [
  3770. expect.objectContaining({
  3771. kind: "image",
  3772. filename: "demo.png",
  3773. mimeType: "image/png",
  3774. dataBase64: "AQID",
  3775. localPath: expect.any(String),
  3776. }),
  3777. ],
  3778. }),
  3779. );
  3780. expect(legacyTaskService.sendPrompt).toHaveBeenCalledWith(
  3781. expect.objectContaining({
  3782. content: expect.stringContaining("不要下载或访问临时/远程 URL"),
  3783. }),
  3784. );
  3785. service.disposeAll();
  3786. });
  3787. it("adds unsupported bot files to the prompt as cached path context", async () => {
  3788. vi.stubEnv("ZCODE_DATA_BASE_DIR", `/tmp/zcode-bot-files-${Date.now()}`);
  3789. const repo = f.createMemoryRepo(f.baseConfig);
  3790. const legacyTaskService = f.createLegacyTaskService();
  3791. const service = f.createBotsService({
  3792. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3793. legacyTaskService,
  3794. repo: repo as never,
  3795. });
  3796. await bind(service);
  3797. await service.handleInboundMessage({
  3798. botId: "webhook-1",
  3799. text: "总结这个文件",
  3800. attachments: [
  3801. {
  3802. id: "file-1",
  3803. kind: "file",
  3804. filename: "notes.txt",
  3805. mimeType: "text/plain",
  3806. dataBase64: Buffer.from("hello").toString("base64"),
  3807. },
  3808. ],
  3809. actor,
  3810. });
  3811. expect(legacyTaskService.createTask).toHaveBeenCalledWith(
  3812. expect.objectContaining({ v4Create: true }),
  3813. );
  3814. expect(legacyTaskService.sendPrompt).toHaveBeenCalledWith(
  3815. expect.objectContaining({
  3816. content: expect.stringContaining(
  3817. "总结这个文件\n\n附件:notes.txt (text/plain, 5B),已保存到:",
  3818. ),
  3819. attachments: undefined,
  3820. }),
  3821. );
  3822. service.disposeAll();
  3823. });
  3824. it("returns an actionable attachment download error instead of provider internals", async () => {
  3825. vi.stubGlobal(
  3826. "fetch",
  3827. vi.fn(async () => new Response("missing", { status: 404 })),
  3828. );
  3829. const repo = f.createMemoryRepo(f.baseConfig);
  3830. const legacyTaskService = f.createLegacyTaskService();
  3831. const service = f.createBotsService({
  3832. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3833. legacyTaskService,
  3834. repo: repo as never,
  3835. });
  3836. await bind(service);
  3837. const replies = await service.handleInboundMessage({
  3838. botId: "webhook-1",
  3839. text: "看一下这个附件",
  3840. attachments: [
  3841. {
  3842. id: "file-404",
  3843. kind: "file",
  3844. filename: "missing.txt",
  3845. mimeType: "text/plain",
  3846. downloadUrl: "https://example.test/missing.txt",
  3847. },
  3848. ],
  3849. actor,
  3850. });
  3851. expect(replies.map((reply) => reply.text)).toEqual([
  3852. "附件处理失败:无法下载附件。文件可能已过期、已撤回,或机器人没有读取权限。请重新发送附件后再试。",
  3853. ]);
  3854. expect(legacyTaskService.createTask).not.toHaveBeenCalled();
  3855. service.disposeAll();
  3856. });
  3857. it("blocks a disconnected remote workspace message without reconnecting", async () => {
  3858. const repo = f.createMemoryRepo(f.baseConfig);
  3859. const legacyTaskService = f.createLegacyTaskService();
  3860. const isConnected = vi.fn(async () => false);
  3861. const ensureConnected = vi.fn(async () => ({ ok: true }));
  3862. const getLegacyTaskService = vi.fn(async () => legacyTaskService);
  3863. const service = f.createBotsService({
  3864. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3865. legacyTaskService,
  3866. remoteWorkspaceService: {
  3867. isConnected,
  3868. ensureConnected,
  3869. getLegacyTaskService,
  3870. },
  3871. repo: repo as never,
  3872. });
  3873. await bind(service);
  3874. const replies = await service.handleInboundMessage({
  3875. botId: "webhook-1",
  3876. text: "请检查当前项目",
  3877. actor,
  3878. });
  3879. expect(replies.map((reply) => reply.text)).toEqual([
  3880. "当前远端项目 /tmp/workspace 未连接。请先发送 **/重连**,连接恢复后再重试。上一条请求未执行。",
  3881. ]);
  3882. expect(isConnected).toHaveBeenCalledWith({
  3883. workspacePath: "/tmp/workspace",
  3884. workspaceIdentity: "ssh://host/tmp/workspace",
  3885. });
  3886. expect(ensureConnected).not.toHaveBeenCalled();
  3887. expect(getLegacyTaskService).not.toHaveBeenCalled();
  3888. expect(legacyTaskService.createTask).not.toHaveBeenCalled();
  3889. service.disposeAll();
  3890. });
  3891. it("returns a clear reconnect failure from /reconnect", async () => {
  3892. const repo = f.createMemoryRepo(f.baseConfig);
  3893. const legacyTaskService = f.createLegacyTaskService();
  3894. const ensureConnected = vi.fn(async () => ({
  3895. ok: false,
  3896. message: "SSH 认证失败",
  3897. }));
  3898. const service = f.createBotsService({
  3899. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3900. legacyTaskService,
  3901. remoteWorkspaceService: {
  3902. isConnected: vi.fn(async () => false),
  3903. ensureConnected,
  3904. getLegacyTaskService: vi.fn(async () => legacyTaskService),
  3905. },
  3906. repo: repo as never,
  3907. });
  3908. await bind(service);
  3909. const replies = await service.handleInboundMessage({
  3910. botId: "webhook-1",
  3911. text: "/reconnect",
  3912. actor,
  3913. });
  3914. expect(replies.map((reply) => reply.text)).toEqual([
  3915. "当前远端项目 /tmp/workspace 重连失败:SSH 认证失败\n上一条请求没有执行。",
  3916. ]);
  3917. expect(ensureConnected).toHaveBeenCalledWith({
  3918. workspacePath: "/tmp/workspace",
  3919. workspaceIdentity: "ssh://host/tmp/workspace",
  3920. });
  3921. expect(legacyTaskService.createTask).not.toHaveBeenCalled();
  3922. service.disposeAll();
  3923. });
  3924. it("blocks remote runtime commands when reconnect service is unavailable", async () => {
  3925. const repo = f.createMemoryRepo(f.baseConfig);
  3926. const legacyTaskService = f.createLegacyTaskService();
  3927. const service = f.createBotsService({
  3928. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3929. legacyTaskService,
  3930. remoteWorkspaceService: undefined,
  3931. repo: repo as never,
  3932. });
  3933. await bind(service);
  3934. const replies = await service.handleInboundMessage({
  3935. botId: "webhook-1",
  3936. text: "/model",
  3937. actor,
  3938. });
  3939. expect(replies.map((reply) => reply.text)).toEqual([
  3940. "当前远端项目 /tmp/workspace 未连接。请先发送 **/重连**,连接恢复后再重试。上一条请求未执行。",
  3941. ]);
  3942. expect(legacyTaskService.createTask).not.toHaveBeenCalled();
  3943. service.disposeAll();
  3944. });
  3945. it("switches to a disconnected remote workspace without reconnecting", async () => {
  3946. const repo = f.createMemoryRepo(f.baseConfig);
  3947. const legacyTaskService = f.createLegacyTaskService();
  3948. const ensureConnected = vi.fn(async () => ({ ok: true }));
  3949. const getLegacyTaskService = vi.fn(async () => legacyTaskService);
  3950. const service = f.createBotsService({
  3951. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3952. legacyTaskService,
  3953. remoteWorkspaceService: {
  3954. isConnected: vi.fn(async () => false),
  3955. ensureConnected,
  3956. getLegacyTaskService,
  3957. },
  3958. repo: repo as never,
  3959. });
  3960. await bind(service);
  3961. const replies = await service.handleInboundMessage({
  3962. botId: "webhook-1",
  3963. text: "/workspace 1",
  3964. actor,
  3965. });
  3966. expect(replies.map((reply) => reply.text)).toEqual([
  3967. [
  3968. "工作区: workspace",
  3969. "模型: -",
  3970. "------",
  3971. "任务: 草稿",
  3972. "状态: 远端未连接",
  3973. "当前远端项目 /tmp/workspace 未连接。请发送 **/重连** 恢复连接。",
  3974. ].join("\n"),
  3975. ]);
  3976. expect(ensureConnected).not.toHaveBeenCalled();
  3977. expect(getLegacyTaskService).not.toHaveBeenCalled();
  3978. service.disposeAll();
  3979. });
  3980. it("allows help and lightweight status when reconnect service is unavailable", async () => {
  3981. const repo = f.createMemoryRepo(f.baseConfig);
  3982. const legacyTaskService = f.createLegacyTaskService();
  3983. const service = f.createBotsService({
  3984. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  3985. legacyTaskService,
  3986. remoteWorkspaceService: undefined,
  3987. repo: repo as never,
  3988. });
  3989. await bind(service);
  3990. vi.mocked(legacyTaskService.listTasks).mockClear();
  3991. const helpReplies = await service.handleInboundMessage({
  3992. botId: "webhook-1",
  3993. text: "/help",
  3994. actor,
  3995. });
  3996. const statusReplies = await service.handleInboundMessage({
  3997. botId: "webhook-1",
  3998. text: "/status",
  3999. actor,
  4000. });
  4001. expect(helpReplies[0]?.text).toContain("ZCode 机器人命令");
  4002. expect(statusReplies[0]?.text).toContain("状态: 远端未连接");
  4003. expect(statusReplies[0]?.text).toContain("**/重连**");
  4004. expect(legacyTaskService.listTasks).not.toHaveBeenCalled();
  4005. expect(legacyTaskService.createTask).not.toHaveBeenCalled();
  4006. service.disposeAll();
  4007. });
  4008. it("reconnects the current remote workspace through /reconnect", async () => {
  4009. const repo = f.createMemoryRepo(f.baseConfig);
  4010. const legacyTaskService = f.createLegacyTaskService();
  4011. const isConnected = vi.fn(async () => false);
  4012. const ensureConnected = vi.fn(async () => ({ ok: true }));
  4013. const service = f.createBotsService({
  4014. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  4015. legacyTaskService,
  4016. remoteWorkspaceService: {
  4017. isConnected,
  4018. ensureConnected,
  4019. getZCodeTaskService: vi.fn(async () => legacyTaskService),
  4020. },
  4021. repo: repo as never,
  4022. });
  4023. await bind(service);
  4024. const replies = await service.handleInboundMessage({
  4025. botId: "webhook-1",
  4026. text: "/reconnect",
  4027. actor,
  4028. });
  4029. expect(replies[0]?.text).toContain("工作区: workspace");
  4030. expect(replies[0]?.text).toContain("状态:");
  4031. expect(ensureConnected).toHaveBeenCalledWith({
  4032. workspacePath: "/tmp/workspace",
  4033. workspaceIdentity: "ssh://host/tmp/workspace",
  4034. });
  4035. expect(legacyTaskService.createTask).not.toHaveBeenCalled();
  4036. service.disposeAll();
  4037. });
  4038. it("sends reconnect callback starting status before reconnect finishes", async () => {
  4039. const repo = f.createMemoryRepo({
  4040. ...f.baseConfig,
  4041. bots: [
  4042. {
  4043. ...f.baseConfig.bots[0]!,
  4044. webhookUrl: "https://example.test/outbound",
  4045. },
  4046. ],
  4047. });
  4048. const legacyTaskService = f.createLegacyTaskService();
  4049. const reconnectDeferred = createDeferred<{ ok: boolean }>();
  4050. const sentTexts: string[] = [];
  4051. const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
  4052. const urlText = url instanceof Request ? url.url : String(url);
  4053. if (urlText !== "https://example.test/outbound") {
  4054. return new Response("{}", { status: 200 });
  4055. }
  4056. const body =
  4057. typeof init?.body === "string" ? (JSON.parse(init.body) as { text?: string }) : {};
  4058. sentTexts.push(body.text ?? "");
  4059. return new Response("{}", { status: 200 });
  4060. });
  4061. vi.stubGlobal("fetch", fetchMock);
  4062. const service = f.createBotsService({
  4063. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  4064. legacyTaskService,
  4065. remoteWorkspaceService: {
  4066. isConnected: vi.fn(async () => false),
  4067. ensureConnected: vi.fn(() => reconnectDeferred.promise),
  4068. getLegacyTaskService: vi.fn(async () => legacyTaskService),
  4069. },
  4070. repo: repo as never,
  4071. });
  4072. await bind(service);
  4073. const callback = service.handleProviderCallbackResponse("webhook", {
  4074. botId: "webhook-1",
  4075. webhookSecret: "secret",
  4076. text: "/reconnect",
  4077. userId: "user-1",
  4078. });
  4079. await vi.waitFor(() =>
  4080. expect(sentTexts).toEqual(["当前远端项目 /tmp/workspace 未连接,正在为你重连..."]),
  4081. );
  4082. reconnectDeferred.resolve({ ok: true });
  4083. await callback;
  4084. expect(sentTexts).toEqual([
  4085. "当前远端项目 /tmp/workspace 未连接,正在为你重连...",
  4086. expect.stringContaining("工作区: workspace"),
  4087. ]);
  4088. service.disposeAll();
  4089. });
  4090. it("deduplicates repeated /reconnect delivery for the same remote workspace", async () => {
  4091. const repo = f.createMemoryRepo(f.baseConfig);
  4092. const legacyTaskService = f.createLegacyTaskService();
  4093. const reconnectDeferred = createDeferred<{ ok: boolean }>();
  4094. const isConnected = vi.fn(async () => false);
  4095. const ensureConnected = vi.fn(() => reconnectDeferred.promise);
  4096. const service = f.createBotsService({
  4097. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  4098. legacyTaskService,
  4099. remoteWorkspaceService: {
  4100. isConnected,
  4101. ensureConnected,
  4102. getLegacyTaskService: vi.fn(async () => legacyTaskService),
  4103. },
  4104. repo: repo as never,
  4105. });
  4106. await bind(service);
  4107. isConnected.mockClear();
  4108. ensureConnected.mockClear();
  4109. const firstReconnect = service.handleInboundMessage({
  4110. botId: "webhook-1",
  4111. text: "/重连",
  4112. actor,
  4113. });
  4114. await vi.waitFor(() => expect(ensureConnected).toHaveBeenCalledTimes(1));
  4115. const duplicateReconnect = service.handleInboundMessage({
  4116. botId: "webhook-1",
  4117. text: "/重连",
  4118. actor,
  4119. });
  4120. reconnectDeferred.resolve({ ok: true });
  4121. await expect(firstReconnect).resolves.toEqual([
  4122. expect.objectContaining({
  4123. text: expect.stringContaining("工作区: workspace"),
  4124. }),
  4125. ]);
  4126. await expect(duplicateReconnect).resolves.toEqual([]);
  4127. const immediateRetry = await service.handleInboundMessage({
  4128. botId: "webhook-1",
  4129. text: "/重连",
  4130. actor,
  4131. });
  4132. expect(immediateRetry).toEqual([]);
  4133. expect(ensureConnected).toHaveBeenCalledTimes(1);
  4134. service.disposeAll();
  4135. });
  4136. it("deduplicates replayed /reconnect provider message ids", async () => {
  4137. const repo = f.createMemoryRepo(f.baseConfig);
  4138. const legacyTaskService = f.createLegacyTaskService();
  4139. const isConnected = vi.fn(async () => false);
  4140. const ensureConnected = vi.fn(async () => ({ ok: true }));
  4141. const service = f.createBotsService({
  4142. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  4143. legacyTaskService,
  4144. remoteWorkspaceService: {
  4145. isConnected,
  4146. ensureConnected,
  4147. getLegacyTaskService: vi.fn(async () => legacyTaskService),
  4148. },
  4149. repo: repo as never,
  4150. });
  4151. await bind(service);
  4152. const replayedActor = { ...actor, providerMessageId: "provider-message-1" };
  4153. const firstReplies = await service.handleInboundMessage({
  4154. botId: "webhook-1",
  4155. text: "/重连",
  4156. actor: replayedActor,
  4157. });
  4158. const replayReplies = await service.handleInboundMessage({
  4159. botId: "webhook-1",
  4160. text: "/重连",
  4161. actor: replayedActor,
  4162. });
  4163. expect(firstReplies[0]?.text).toContain("工作区: workspace");
  4164. expect(firstReplies[0]?.text).toContain("状态:");
  4165. expect(replayReplies).toEqual([]);
  4166. expect(ensureConnected).toHaveBeenCalledTimes(1);
  4167. service.disposeAll();
  4168. });
  4169. it("deduplicates replayed provider callbacks before executing messages", async () => {
  4170. const repo = f.createMemoryRepo(f.baseConfig);
  4171. const legacyTaskService = f.createLegacyTaskService();
  4172. const service = f.createBotsService({
  4173. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  4174. legacyTaskService,
  4175. remoteWorkspaceService: {
  4176. isConnected: vi.fn(async () => true),
  4177. ensureConnected: vi.fn(async () => ({ ok: true })),
  4178. getZCodeTaskService: vi.fn(async () => legacyTaskService),
  4179. getModelSelectionService: vi.fn(async () =>
  4180. f.createModelSelectionService([{ id: "glm", name: "GLM", models: ["default"] }]),
  4181. ),
  4182. },
  4183. repo: repo as never,
  4184. });
  4185. await bind(service);
  4186. const payload = {
  4187. botId: "webhook-1",
  4188. webhookSecret: "secret",
  4189. messageId: "message-hello-1",
  4190. text: "hello",
  4191. userId: "user-1",
  4192. };
  4193. const first = await service.handleProviderCallbackResponse("webhook", payload);
  4194. const replay = await service.handleProviderCallbackResponse("webhook", payload);
  4195. expect(first.ok).toBe(true);
  4196. expect(first.replies).toEqual([]);
  4197. expect(replay.replies).toEqual([]);
  4198. expect(legacyTaskService.createTask).toHaveBeenCalledTimes(1);
  4199. service.disposeAll();
  4200. });
  4201. it("turns missing session callback failures into a /new task hint", async () => {
  4202. const missingSessionId = "9a18d1e7-24a0-47ba-9747-d3502d8b15b";
  4203. const repo = f.createMemoryRepo(
  4204. {
  4205. ...f.baseConfig,
  4206. bots: [
  4207. {
  4208. ...f.baseConfig.bots[0]!,
  4209. providerUserId: "user-1",
  4210. },
  4211. ],
  4212. },
  4213. {
  4214. version: 3,
  4215. bots: {
  4216. "webhook-1": {
  4217. botId: "webhook-1",
  4218. workspacePath: "/tmp/workspace",
  4219. workspaceIdentity: "ssh://host/tmp/workspace",
  4220. workspaceId: "ssh://host/tmp/workspace",
  4221. mode: "task",
  4222. activeTaskId: missingSessionId,
  4223. updatedAt: Date.now(),
  4224. },
  4225. },
  4226. },
  4227. );
  4228. const legacyTaskService = f.createLegacyTaskService();
  4229. vi.mocked(legacyTaskService.resumeTask).mockRejectedValueOnce(
  4230. new Error(`Session not found: ${missingSessionId}`),
  4231. );
  4232. const service = f.createBotsService({
  4233. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  4234. legacyTaskService,
  4235. repo: repo as never,
  4236. });
  4237. const response = await service.handleProviderCallbackResponse("webhook", {
  4238. botId: "webhook-1",
  4239. webhookSecret: "secret",
  4240. messageId: "message-stale-session-1",
  4241. text: "继续",
  4242. userId: "user-1",
  4243. });
  4244. expect(response).toMatchObject({ ok: false, status: 503 });
  4245. expect(response.replies[0]?.text).toContain("/new task");
  4246. expect(response.replies[0]?.text).not.toContain(missingSessionId);
  4247. expect(response.replies[0]?.text).not.toContain("处理机器人回调失败");
  4248. service.disposeAll();
  4249. });
  4250. it("uses draftOptions when creating a task", async () => {
  4251. const repo = f.createMemoryRepo(f.baseConfig, {
  4252. version: 3,
  4253. bots: {
  4254. "webhook-1": {
  4255. botId: "webhook-1",
  4256. workspacePath: "/tmp/workspace",
  4257. workspaceIdentity: "ssh://host/tmp/workspace",
  4258. workspaceId: "ssh://host/tmp/workspace",
  4259. mode: "draft",
  4260. activeTaskId: null,
  4261. draftOptions: {
  4262. provider: "codex",
  4263. modelSelection: {
  4264. providerId: "glm",
  4265. modelId: "gpt-5.4",
  4266. options: { reasoningLevel: "medium" },
  4267. },
  4268. mode: "plan",
  4269. },
  4270. updatedAt: Date.now(),
  4271. },
  4272. },
  4273. });
  4274. const legacyTaskService = f.createLegacyTaskService();
  4275. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([
  4276. {
  4277. id: "mode",
  4278. category: "mode",
  4279. type: "select",
  4280. currentValue: "default",
  4281. options: [{ value: "yolo", name: "Yolo" }],
  4282. },
  4283. {
  4284. id: "thought_level",
  4285. category: "thought_level",
  4286. type: "select",
  4287. currentValue: "low",
  4288. options: [{ value: "medium", name: "Medium" }],
  4289. },
  4290. ]);
  4291. const zcodeSessionService = f.createZCodeSessionService(
  4292. f.createZCodeSessionSettingsFromConfigOptions([
  4293. {
  4294. id: "mode",
  4295. category: "mode",
  4296. type: "select",
  4297. currentValue: "plan",
  4298. options: [{ value: "plan", name: "Plan" }],
  4299. },
  4300. {
  4301. id: "thought_level",
  4302. category: "thought_level",
  4303. type: "select",
  4304. currentValue: "medium",
  4305. options: [{ value: "medium", name: "Medium" }],
  4306. },
  4307. ]),
  4308. );
  4309. const service = f.createBotsService({
  4310. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  4311. legacyTaskService,
  4312. zcodeSessionService,
  4313. repo: repo as never,
  4314. });
  4315. await bind(service);
  4316. await service.handleInboundMessage({
  4317. botId: "webhook-1",
  4318. text: "start",
  4319. actor,
  4320. });
  4321. expect(legacyTaskService.createTask).toHaveBeenCalledWith(
  4322. expect.objectContaining({
  4323. modelSelection: {
  4324. providerId: "glm",
  4325. modelId: "gpt-5.4",
  4326. options: { reasoningLevel: "medium" },
  4327. },
  4328. }),
  4329. );
  4330. expect(legacyTaskService.setMode).toHaveBeenCalledWith(
  4331. expect.objectContaining({ mode: "yolo" }),
  4332. );
  4333. expect(legacyTaskService.setConfigOption).not.toHaveBeenCalled();
  4334. service.disposeAll();
  4335. });
  4336. it("validates inherited thought level against the newly selected task model", async () => {
  4337. const repo = f.createMemoryRepo(f.weixinConfig, {
  4338. version: 3,
  4339. bots: {
  4340. "weixin-1": {
  4341. botId: "weixin-1",
  4342. workspacePath: "/tmp/workspace",
  4343. workspaceIdentity: "ssh://host/tmp/workspace",
  4344. workspaceId: "ssh://host/tmp/workspace",
  4345. mode: "draft",
  4346. activeTaskId: null,
  4347. draftOptions: {
  4348. provider: "glm",
  4349. model: "custom:deepseek:deepseek-v4-flash",
  4350. thoughtLevel: "enabled",
  4351. },
  4352. updatedAt: Date.now(),
  4353. },
  4354. },
  4355. });
  4356. const legacyTaskService = f.createLegacyTaskService();
  4357. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([
  4358. {
  4359. id: "mode",
  4360. category: "mode",
  4361. type: "select",
  4362. currentValue: "default",
  4363. options: [{ value: "yolo", name: "Yolo" }],
  4364. },
  4365. {
  4366. id: "thought_level",
  4367. category: "thought_level",
  4368. type: "select",
  4369. currentValue: "max",
  4370. options: [{ value: "max", name: "Max" }],
  4371. },
  4372. ]);
  4373. const service = f.createBotsService({
  4374. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  4375. legacyTaskService,
  4376. repo: repo as never,
  4377. });
  4378. const replies = await service.handleInboundMessage({
  4379. botId: "weixin-1",
  4380. text: "hello",
  4381. actor: weixinActor,
  4382. });
  4383. expect(replies).toEqual([]);
  4384. expect(legacyTaskService.setMode).toHaveBeenCalledWith(
  4385. expect.objectContaining({ mode: "yolo" }),
  4386. );
  4387. expect(legacyTaskService.setConfigOption).not.toHaveBeenCalled();
  4388. expect(legacyTaskService.createTask).toHaveBeenCalledWith(
  4389. expect.objectContaining({ v4Create: true }),
  4390. );
  4391. expect(legacyTaskService.sendPrompt).toHaveBeenCalledWith(
  4392. expect.objectContaining({ content: "hello" }),
  4393. );
  4394. service.disposeAll();
  4395. });
  4396. it("keeps Bot state in draft and deletes the provisional task when initial config fails", async () => {
  4397. const repo = f.createMemoryRepo(f.weixinConfig, {
  4398. version: 3,
  4399. bots: {
  4400. "weixin-1": {
  4401. botId: "weixin-1",
  4402. workspacePath: "/tmp/workspace",
  4403. workspaceIdentity: "ssh://host/tmp/workspace",
  4404. workspaceId: "ssh://host/tmp/workspace",
  4405. mode: "draft",
  4406. activeTaskId: null,
  4407. draftOptions: { provider: "glm" },
  4408. updatedAt: Date.now(),
  4409. },
  4410. },
  4411. });
  4412. const legacyTaskService = f.createLegacyTaskService();
  4413. Object.assign(legacyTaskService, { deleteTask: vi.fn(async () => undefined) });
  4414. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([
  4415. {
  4416. id: "mode",
  4417. category: "mode",
  4418. type: "select",
  4419. currentValue: "default",
  4420. options: [{ value: "yolo", name: "Yolo" }],
  4421. },
  4422. ]);
  4423. vi.mocked(legacyTaskService.setMode).mockRejectedValueOnce(
  4424. new Error("Unsupported reasoning effort: enabled"),
  4425. );
  4426. const service = f.createBotsService({
  4427. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  4428. legacyTaskService,
  4429. repo: repo as never,
  4430. });
  4431. await expect(
  4432. service.handleInboundMessage({
  4433. botId: "weixin-1",
  4434. text: "hello",
  4435. actor: weixinActor,
  4436. }),
  4437. ).rejects.toThrow("Unsupported reasoning effort: enabled");
  4438. expect(legacyTaskService.deleteTask).toHaveBeenCalledWith({
  4439. taskId: "task-1",
  4440. workspacePath: "/tmp/workspace",
  4441. workspaceIdentity: "ssh://host/tmp/workspace",
  4442. });
  4443. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  4444. mode: "draft",
  4445. activeTaskId: null,
  4446. });
  4447. expect(legacyTaskService.sendPrompt).not.toHaveBeenCalled();
  4448. service.disposeAll();
  4449. });
  4450. it("keeps the active task when /new is requested while the task is running", async () => {
  4451. const repo = f.createMemoryRepo(f.baseConfig);
  4452. const legacyTaskService = f.createLegacyTaskService();
  4453. const service = f.createBotsService({
  4454. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  4455. legacyTaskService,
  4456. repo: repo as never,
  4457. });
  4458. await bind(service);
  4459. await service.handleInboundMessage({
  4460. botId: "webhook-1",
  4461. text: "first",
  4462. actor,
  4463. });
  4464. vi.mocked(legacyTaskService.createTask).mockClear();
  4465. const newReplies = await service.handleInboundMessage({
  4466. botId: "webhook-1",
  4467. text: "/new",
  4468. actor,
  4469. });
  4470. await service.handleInboundMessage({
  4471. botId: "webhook-1",
  4472. text: "second",
  4473. actor,
  4474. });
  4475. expect(newReplies[0]?.text).toContain("当前任务正在运行");
  4476. expect(legacyTaskService.createTask).not.toHaveBeenCalled();
  4477. expect((await repo.readState()).bots["webhook-1"]).toMatchObject({
  4478. activeTaskId: "task-1",
  4479. mode: "task",
  4480. });
  4481. service.disposeAll();
  4482. });
  4483. it("blocks context and config selection lists while the current task is running", async () => {
  4484. const repo = f.createMemoryRepo(f.weixinConfig);
  4485. const legacyTaskService = f.createLegacyTaskService();
  4486. const service = f.createBotsService({
  4487. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  4488. legacyTaskService,
  4489. repo: repo as never,
  4490. });
  4491. await service.handleInboundMessage({
  4492. botId: "weixin-1",
  4493. text: "first",
  4494. actor: weixinActor,
  4495. });
  4496. await service.handleInboundMessage({
  4497. botId: "weixin-1",
  4498. text: "run task",
  4499. actor: weixinActor,
  4500. });
  4501. for (const text of ["/task", "/workspace", "/model", "/think"]) {
  4502. const replies = await service.handleInboundMessage({
  4503. botId: "weixin-1",
  4504. text,
  4505. actor: weixinActor,
  4506. });
  4507. expect(replies[0]?.text).toContain("当前任务正在运行");
  4508. expect(replies[0]).not.toHaveProperty("selection");
  4509. }
  4510. const modeReplies = await service.handleInboundMessage({
  4511. botId: "weixin-1",
  4512. text: "/mode",
  4513. actor: weixinActor,
  4514. });
  4515. expect(modeReplies[0]?.text).toContain("yolo");
  4516. expect(modeReplies[0]).not.toHaveProperty("selection");
  4517. service.disposeAll();
  4518. });
  4519. it("creates /new draftOptions from the previous active task config", async () => {
  4520. const repo = f.createMemoryRepo(f.weixinConfig, {
  4521. version: 3,
  4522. bots: {
  4523. "weixin-1": {
  4524. botId: "weixin-1",
  4525. workspacePath: "/tmp/workspace",
  4526. workspaceIdentity: "ssh://host/tmp/workspace",
  4527. workspaceId: "ssh://host/tmp/workspace",
  4528. mode: "task",
  4529. activeTaskId: "task-1",
  4530. updatedAt: Date.now(),
  4531. },
  4532. },
  4533. });
  4534. const legacyTaskService = f.createLegacyTaskService();
  4535. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  4536. {
  4537. taskId: "task-1",
  4538. title: "Previous task",
  4539. workspacePath: "/tmp/workspace",
  4540. workspaceIdentity: "ssh://host/tmp/workspace",
  4541. provider: "claude",
  4542. model: "fallback-model",
  4543. mode: "fallback-mode",
  4544. },
  4545. ]);
  4546. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([
  4547. {
  4548. id: "model",
  4549. category: "model",
  4550. type: "select",
  4551. currentValue: "claude-sonnet",
  4552. options: [{ value: "claude-sonnet", name: "Claude Sonnet" }],
  4553. },
  4554. {
  4555. id: "mode",
  4556. category: "mode",
  4557. type: "select",
  4558. currentValue: "plan",
  4559. options: [{ value: "plan", name: "Plan" }],
  4560. },
  4561. {
  4562. id: "thoughtLevel",
  4563. category: "thought_level",
  4564. type: "select",
  4565. currentValue: "medium",
  4566. options: [{ value: "medium", name: "Medium" }],
  4567. },
  4568. ]);
  4569. vi.mocked(legacyTaskService.getTaskModelSelection).mockResolvedValue({
  4570. providerId: "glm",
  4571. modelId: "claude-sonnet",
  4572. options: { reasoningLevel: "medium" },
  4573. });
  4574. const service = f.createBotsService({
  4575. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  4576. legacyTaskService,
  4577. repo: repo as never,
  4578. });
  4579. const replies = await service.handleInboundMessage({
  4580. botId: "weixin-1",
  4581. text: "/new",
  4582. actor: weixinActor,
  4583. });
  4584. expect(replies[0]?.text).not.toContain("Provider:");
  4585. expect(replies[0]?.text).toContain("任务: 草稿");
  4586. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  4587. mode: "draft",
  4588. activeTaskId: null,
  4589. draftOptions: {
  4590. provider: "glm",
  4591. modelSelection: {
  4592. providerId: "glm",
  4593. modelId: "claude-sonnet",
  4594. options: { reasoningLevel: "medium" },
  4595. },
  4596. },
  4597. });
  4598. const statusReplies = await service.handleInboundMessage({
  4599. botId: "weixin-1",
  4600. text: "/status",
  4601. actor: weixinActor,
  4602. });
  4603. expect(statusReplies[0]?.text).not.toContain("Provider:");
  4604. expect(statusReplies[0]?.text).toContain("模型: claude-sonnet");
  4605. expect(statusReplies[0]?.text).toContain("任务: 草稿");
  4606. service.disposeAll();
  4607. });
  4608. it("updates draftOptions through model, mode, think, and cli before creating a task", async () => {
  4609. const repo = f.createMemoryRepo(f.weixinConfig, {
  4610. version: 3,
  4611. bots: {
  4612. "weixin-1": {
  4613. botId: "weixin-1",
  4614. workspacePath: "/tmp/workspace",
  4615. workspaceIdentity: "ssh://host/tmp/workspace",
  4616. workspaceId: "ssh://host/tmp/workspace",
  4617. mode: "draft",
  4618. activeTaskId: null,
  4619. draftOptions: {
  4620. provider: "codex",
  4621. model: "gpt-5.3",
  4622. mode: "default",
  4623. thoughtLevel: "low",
  4624. },
  4625. updatedAt: Date.now(),
  4626. },
  4627. },
  4628. });
  4629. const legacyTaskService = f.createLegacyTaskService();
  4630. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([
  4631. {
  4632. id: "mode",
  4633. category: "mode",
  4634. type: "select",
  4635. currentValue: "default",
  4636. options: [{ value: "yolo", name: "Yolo" }],
  4637. },
  4638. {
  4639. id: "thought_level",
  4640. category: "thought_level",
  4641. type: "select",
  4642. currentValue: "low",
  4643. options: [{ value: "medium", name: "Medium" }],
  4644. },
  4645. ]);
  4646. const zcodeSessionService = f.createZCodeSessionService(
  4647. f.createZCodeSessionSettingsFromConfigOptions([
  4648. {
  4649. id: "model",
  4650. category: "model",
  4651. type: "select",
  4652. currentValue: "gpt-5.3",
  4653. options: [
  4654. { value: "gpt-5.3", name: "GPT-5.3" },
  4655. { value: "gpt-5.4", name: "GPT-5.4" },
  4656. ],
  4657. },
  4658. {
  4659. id: "mode",
  4660. category: "mode",
  4661. type: "select",
  4662. currentValue: "plan",
  4663. options: [{ value: "plan", name: "Plan" }],
  4664. },
  4665. {
  4666. id: "thought_level",
  4667. category: "thought_level",
  4668. type: "select",
  4669. currentValue: "medium",
  4670. options: [{ value: "medium", name: "Medium" }],
  4671. },
  4672. ]),
  4673. );
  4674. const service = f.createBotsService({
  4675. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  4676. legacyTaskService,
  4677. zcodeSessionService,
  4678. modelSelectionService: f.createModelSelectionService([
  4679. {
  4680. id: "runtime-provider",
  4681. name: "Runtime Provider",
  4682. endpoints: { baseURL: "https://example.com/v1", paths: { "openai-compatible": "" } },
  4683. defaultKind: "openai-compatible",
  4684. apiKey: "key",
  4685. models: [
  4686. "gpt-5.3",
  4687. {
  4688. id: "gpt-5.4",
  4689. config: {
  4690. optionSpecs: {
  4691. reasoningLevel: {
  4692. values: ["low", "medium", "high"],
  4693. },
  4694. },
  4695. },
  4696. },
  4697. ],
  4698. createdAt: 1,
  4699. updatedAt: 1,
  4700. },
  4701. ]),
  4702. repo: repo as never,
  4703. });
  4704. await service.handleInboundMessage({
  4705. botId: "weixin-1",
  4706. text: "/model",
  4707. actor: weixinActor,
  4708. });
  4709. await service.handleInboundMessage({
  4710. botId: "weixin-1",
  4711. text: "1",
  4712. actor: weixinActor,
  4713. });
  4714. await service.handleInboundMessage({
  4715. botId: "weixin-1",
  4716. text: "2",
  4717. actor: weixinActor,
  4718. });
  4719. expect(
  4720. (await repo.readState()).bots["weixin-1"]?.draftOptions?.modelSelection?.options,
  4721. ).toEqual({ reasoningLevel: "high" });
  4722. await service.handleInboundMessage({
  4723. botId: "weixin-1",
  4724. text: "/mode plan",
  4725. actor: weixinActor,
  4726. });
  4727. await service.handleInboundMessage({
  4728. botId: "weixin-1",
  4729. text: "/think medium",
  4730. actor: weixinActor,
  4731. });
  4732. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  4733. draftOptions: {
  4734. provider: "glm",
  4735. modelSelection: {
  4736. providerId: "runtime-provider",
  4737. modelId: "gpt-5.4",
  4738. options: { reasoningLevel: "medium" },
  4739. },
  4740. mode: "default",
  4741. },
  4742. });
  4743. await service.handleInboundMessage({
  4744. botId: "weixin-1",
  4745. text: "start",
  4746. actor: weixinActor,
  4747. });
  4748. expect(legacyTaskService.createTask).toHaveBeenCalledWith(
  4749. expect.objectContaining({
  4750. provider: "glm",
  4751. modelSelection: {
  4752. providerId: "runtime-provider",
  4753. modelId: "gpt-5.4",
  4754. options: { reasoningLevel: "medium" },
  4755. },
  4756. }),
  4757. );
  4758. expect(legacyTaskService.setMode).toHaveBeenCalledWith(
  4759. expect.objectContaining({ mode: "yolo" }),
  4760. );
  4761. expect(legacyTaskService.setConfigOption).not.toHaveBeenCalled();
  4762. service.disposeAll();
  4763. });
  4764. it("skips stale unsupported draft mode when creating a ZCode Agent task", async () => {
  4765. const repo = f.createMemoryRepo(f.weixinConfig, {
  4766. version: 3,
  4767. bots: {
  4768. "weixin-1": {
  4769. botId: "weixin-1",
  4770. workspacePath: "/tmp/workspace",
  4771. workspaceIdentity: "ssh://host/tmp/workspace",
  4772. workspaceId: "ssh://host/tmp/workspace",
  4773. mode: "draft",
  4774. activeTaskId: null,
  4775. draftOptions: {
  4776. provider: "glm",
  4777. mode: "default",
  4778. },
  4779. updatedAt: Date.now(),
  4780. },
  4781. },
  4782. });
  4783. const legacyTaskService = f.createLegacyTaskService();
  4784. vi.mocked(legacyTaskService.getTaskConfigOptions).mockResolvedValue([
  4785. {
  4786. id: "mode",
  4787. category: "mode",
  4788. type: "select",
  4789. currentValue: "default",
  4790. options: [{ value: "yolo", name: "Yolo" }],
  4791. },
  4792. ]);
  4793. const service = f.createBotsService({
  4794. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  4795. legacyTaskService,
  4796. repo: repo as never,
  4797. });
  4798. await service.handleInboundMessage({
  4799. botId: "weixin-1",
  4800. text: "start",
  4801. actor: weixinActor,
  4802. });
  4803. expect(legacyTaskService.createTask).toHaveBeenCalledWith(
  4804. expect.objectContaining({
  4805. provider: "glm",
  4806. }),
  4807. );
  4808. expect(legacyTaskService.setMode).toHaveBeenCalledWith(
  4809. expect.objectContaining({ mode: "yolo" }),
  4810. );
  4811. service.disposeAll();
  4812. });
  4813. it("blocks task switching while the current task is running", async () => {
  4814. const repo = f.createMemoryRepo(f.weixinConfig);
  4815. const legacyTaskService = f.createLegacyTaskService();
  4816. const service = f.createBotsService({
  4817. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  4818. legacyTaskService,
  4819. repo: repo as never,
  4820. });
  4821. await service.handleInboundMessage({
  4822. botId: "weixin-1",
  4823. text: "first",
  4824. actor: weixinActor,
  4825. });
  4826. await service.handleInboundMessage({
  4827. botId: "weixin-1",
  4828. text: "run task",
  4829. actor: weixinActor,
  4830. });
  4831. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  4832. {
  4833. taskId: "task-1",
  4834. title: "Running task",
  4835. workspacePath: "/tmp/workspace",
  4836. workspaceIdentity: "ssh://host/tmp/workspace",
  4837. },
  4838. {
  4839. taskId: "task-2",
  4840. title: "Second task",
  4841. workspacePath: "/tmp/workspace",
  4842. workspaceIdentity: "ssh://host/tmp/workspace",
  4843. status: "completed",
  4844. },
  4845. ]);
  4846. await service.handleInboundMessage({
  4847. botId: "weixin-1",
  4848. text: "/task",
  4849. actor: weixinActor,
  4850. });
  4851. const replies = await service.handleInboundMessage({
  4852. botId: "weixin-1",
  4853. text: "2",
  4854. actor: weixinActor,
  4855. });
  4856. expect(replies[0]?.text).toContain("当前任务正在运行");
  4857. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  4858. activeTaskId: "task-1",
  4859. mode: "task",
  4860. });
  4861. service.disposeAll();
  4862. });
  4863. it("allows task switching for a legacy active task without persisted status when it is not running", async () => {
  4864. const repo = f.createMemoryRepo(f.weixinConfig, {
  4865. version: 3,
  4866. bots: {
  4867. "weixin-1": {
  4868. botId: "weixin-1",
  4869. workspacePath: "/tmp/workspace",
  4870. workspaceIdentity: "ssh://host/tmp/workspace",
  4871. workspaceId: "ssh://host/tmp/workspace",
  4872. mode: "task",
  4873. activeTaskId: "task-1",
  4874. updatedAt: Date.now(),
  4875. },
  4876. },
  4877. });
  4878. const legacyTaskService = f.createLegacyTaskService();
  4879. vi.mocked(legacyTaskService.listTasks).mockResolvedValue([
  4880. {
  4881. taskId: "task-1",
  4882. title: "Legacy task",
  4883. workspacePath: "/tmp/workspace",
  4884. workspaceIdentity: "ssh://host/tmp/workspace",
  4885. },
  4886. {
  4887. taskId: "task-2",
  4888. title: "Second task",
  4889. workspacePath: "/tmp/workspace",
  4890. workspaceIdentity: "ssh://host/tmp/workspace",
  4891. status: "completed",
  4892. },
  4893. ]);
  4894. const service = f.createBotsService({
  4895. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  4896. legacyTaskService,
  4897. repo: repo as never,
  4898. });
  4899. await service.handleInboundMessage({
  4900. botId: "weixin-1",
  4901. text: "/task",
  4902. actor: weixinActor,
  4903. });
  4904. const replies = await service.handleInboundMessage({
  4905. botId: "weixin-1",
  4906. text: "2",
  4907. actor: weixinActor,
  4908. });
  4909. expect(replies[0]?.text).toContain("Second task");
  4910. expect((await repo.readState()).bots["weixin-1"]).toMatchObject({
  4911. activeTaskId: "task-2",
  4912. mode: "task",
  4913. });
  4914. service.disposeAll();
  4915. });
  4916. it("preserves Plan render context after expanding a Feishu custom answer", async () => {
  4917. let messagePostCount = 0;
  4918. const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
  4919. if (url.endsWith("/tenant_access_token/internal")) {
  4920. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token" }));
  4921. }
  4922. if (url.includes("/open-apis/im/v1/messages?receive_id_type=") && init?.method === "POST") {
  4923. messagePostCount += 1;
  4924. return new Response(
  4925. JSON.stringify({ code: 0, data: { message_id: `om_plan_${messagePostCount}` } }),
  4926. );
  4927. }
  4928. return new Response(JSON.stringify({ code: 0 }));
  4929. });
  4930. vi.stubGlobal("fetch", fetchMock);
  4931. const repo = f.createMemoryRepo(f.feishuConfig, {
  4932. version: 3,
  4933. bots: {
  4934. "feishu-1": {
  4935. botId: "feishu-1",
  4936. workspacePath: "/tmp/workspace",
  4937. workspaceIdentity: "ssh://host/tmp/workspace",
  4938. workspaceId: "ssh://host/tmp/workspace",
  4939. mode: "task",
  4940. activeTaskId: "task-1",
  4941. updatedAt: Date.now(),
  4942. },
  4943. },
  4944. });
  4945. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  4946. const service = f.createBotsService({
  4947. credentialService: f.createCredentialService({ "feishu-secret": "secret" }),
  4948. legacyTaskService: {
  4949. ...f.createLegacyTaskService(),
  4950. onDynamicTaskEvent: vi.fn(
  4951. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  4952. streamListeners.push(listener);
  4953. return { dispose() {} };
  4954. },
  4955. ),
  4956. },
  4957. repo: repo as never,
  4958. });
  4959. await service.handleInboundMessage({ botId: "feishu-1", text: "启动任务", actor: feishuActor });
  4960. await streamListeners[0]?.({
  4961. type: "elicitation_request",
  4962. taskId: "task-1",
  4963. traceId: "trace-plan",
  4964. requestId: "elicit-plan",
  4965. message: "Review this implementation plan.",
  4966. options: [{ value: "approve", label: "Approve" }],
  4967. schema: {
  4968. interaction: "plan_approval",
  4969. toolName: "ExitPlanMode",
  4970. plan: "# Snake plan\n\n1. Build board\n2. Add controls",
  4971. },
  4972. });
  4973. const sendCall = fetchMock.mock.calls.find(([url]) =>
  4974. String(url).includes("/open-apis/im/v1/messages"),
  4975. );
  4976. const sendBody = JSON.parse(String(sendCall?.[1]?.body)) as { content?: string };
  4977. const token = String(sendBody.content).match(/\/elicitation ([a-f0-9]{12}) __custom__/u)?.[1];
  4978. const response = await service.handleProviderCallbackResponse("feishu", {
  4979. botId: "feishu-1",
  4980. event: {
  4981. operator: { operator_id: { open_id: "ou_user" } },
  4982. action: {
  4983. behaviors: [
  4984. {
  4985. type: "callback",
  4986. value: { command: `/elicitation ${token} __custom__`, zcodeCardText: "Plan" },
  4987. },
  4988. ],
  4989. },
  4990. context: { card_update_token: "plan-card-token" },
  4991. },
  4992. });
  4993. expect(response.ok).toBe(true);
  4994. expect(response.replies[0]?.elicitation?.schema).toMatchObject({
  4995. interaction: "plan_approval",
  4996. plan: expect.stringContaining("# Snake plan"),
  4997. });
  4998. const formSendCall = fetchMock.mock.calls
  4999. .filter(([url]) => String(url).includes("/open-apis/interactive/v1/card/update"))
  5000. .at(-1);
  5001. const formSendBody = JSON.parse(String(formSendCall?.[1]?.body)) as {
  5002. card?: unknown;
  5003. };
  5004. expect(JSON.stringify(formSendBody.card)).toContain("Add controls");
  5005. expect(JSON.stringify(formSendBody.card)).toContain('"tag":"form"');
  5006. expect((await repo.readState()).bots["feishu-1"]?.pendingElicitation?.renderContext).toEqual({
  5007. kind: "plan_approval",
  5008. plan: "# Snake plan\n\n1. Build board\n2. Add controls",
  5009. });
  5010. service.disposeAll();
  5011. });
  5012. it.each([
  5013. {
  5014. name: "Telegram",
  5015. config: f.telegramConfig,
  5016. botId: "telegram-1",
  5017. actor: {
  5018. provider: "telegram" as const,
  5019. botId: "telegram-1",
  5020. providerUserId: "user-1",
  5021. chatType: "private" as const,
  5022. },
  5023. credentials: { "telegram-token": "token" },
  5024. sendPath: "/sendMessage",
  5025. readText: (body: Record<string, unknown>) => String(body.text),
  5026. readOptions: (body: Record<string, unknown>) => JSON.stringify(body.reply_markup),
  5027. },
  5028. {
  5029. name: "Weixin",
  5030. config: f.weixinConfig,
  5031. botId: "weixin-1",
  5032. actor: weixinActor,
  5033. credentials: { "weixin-token": "token" },
  5034. sendPath: "/sendmessage",
  5035. readText: (body: Record<string, unknown>) => {
  5036. const msg = body.msg as {
  5037. item_list?: Array<{ text_item?: { text?: string } }>;
  5038. };
  5039. return String(msg.item_list?.[0]?.text_item?.text);
  5040. },
  5041. readOptions: (body: Record<string, unknown>) => JSON.stringify(body),
  5042. },
  5043. ])(
  5044. "renders complete plan approval text and both actions for $name",
  5045. async ({
  5046. config,
  5047. botId,
  5048. actor: channelActor,
  5049. credentials,
  5050. sendPath,
  5051. readText,
  5052. readOptions,
  5053. }) => {
  5054. const fetchMock = vi.fn(async () => new Response(JSON.stringify({}), { status: 200 }));
  5055. vi.stubGlobal("fetch", fetchMock);
  5056. const repo = f.createMemoryRepo(config, {
  5057. version: 3,
  5058. bots: {
  5059. [botId]: {
  5060. botId,
  5061. workspacePath: "/tmp/workspace",
  5062. workspaceIdentity: "ssh://host/tmp/workspace",
  5063. workspaceId: "ssh://host/tmp/workspace",
  5064. mode: "task",
  5065. activeTaskId: "task-1",
  5066. updatedAt: Date.now(),
  5067. },
  5068. },
  5069. });
  5070. const streamListeners: Array<(event: ZCodeStreamEvent) => Promise<void> | void> = [];
  5071. const service = f.createBotsService({
  5072. credentialService: f.createCredentialService(credentials),
  5073. legacyTaskService: {
  5074. ...f.createLegacyTaskService(),
  5075. onDynamicTaskEvent: vi.fn(
  5076. () => (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  5077. streamListeners.push(listener);
  5078. return { dispose() {} };
  5079. },
  5080. ),
  5081. },
  5082. repo: repo as never,
  5083. });
  5084. await service.handleInboundMessage({
  5085. botId,
  5086. text: "start",
  5087. actor: channelActor,
  5088. });
  5089. fetchMock.mockClear();
  5090. await streamListeners[0]?.({
  5091. type: "elicitation_request",
  5092. taskId: "task-1",
  5093. traceId: "trace-plan-text",
  5094. requestId: "elicit-plan-text",
  5095. message: "Review this implementation plan.",
  5096. options: [{ value: "approve", label: "Approve" }],
  5097. schema: {
  5098. interaction: "plan_approval",
  5099. toolName: "ExitPlanMode",
  5100. plan: "# Complete plan\n\n1. Build\n2. Verify",
  5101. },
  5102. });
  5103. const sendCall = fetchMock.mock.calls.find(([url]) => String(url).includes(sendPath));
  5104. const body = JSON.parse(String(sendCall?.[1]?.body)) as Record<string, unknown>;
  5105. const text = readText(body);
  5106. expect(text).toContain("# Complete plan");
  5107. expect(text).toContain("1. Build");
  5108. expect(text).toContain("------");
  5109. expect(text).toContain("请审阅此实施计划。");
  5110. const options = `${text}\n${readOptions(body)}`;
  5111. expect(options).toContain("批准");
  5112. expect(options).toContain("自定义回答");
  5113. service.disposeAll();
  5114. },
  5115. );
  5116. it.each([false, true])(
  5117. "resolves Bot draft intent before first creation without rewriting it on reads (incomplete=%s)",
  5118. async (incomplete) => {
  5119. const original = {
  5120. providerId: "account:bigmodel-individual-coding-plan",
  5121. modelId: "GLM-5.3",
  5122. options: { reasoningLevel: "high" },
  5123. };
  5124. const effective = { ...original, providerId: "account:bigmodel-team-coding-plan" };
  5125. const repo = f.createMemoryRepo(f.weixinConfig, {
  5126. version: 3,
  5127. bots: {
  5128. "weixin-1": {
  5129. botId: "weixin-1",
  5130. workspacePath: "/tmp/workspace",
  5131. workspaceId: "/tmp/workspace",
  5132. mode: "draft",
  5133. activeTaskId: null,
  5134. draftOptions: { provider: "glm", mode: "yolo", modelSelection: original },
  5135. updatedAt: Date.now(),
  5136. },
  5137. },
  5138. });
  5139. const getView = vi.fn(async () => ({
  5140. revision: 1,
  5141. providers: [],
  5142. preferredSelection: { providerId: "unrelated", modelId: "default" },
  5143. effectiveSelection: incomplete ? null : effective,
  5144. ...(incomplete ? { selectionIssue: "model-not-found" } : {}),
  5145. }));
  5146. const taskService = f.createLegacyTaskService();
  5147. const service = f.createBotsService({
  5148. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  5149. modelSelectionService: { getView } as never,
  5150. legacyTaskService: taskService,
  5151. repo: repo as never,
  5152. });
  5153. try {
  5154. await service.handleInboundMessage({
  5155. botId: "weixin-1",
  5156. text: "/status",
  5157. actor: weixinActor,
  5158. });
  5159. expect(getView).toHaveBeenCalledWith({ selection: original });
  5160. expect((await repo.readState()).bots["weixin-1"]?.draftOptions?.modelSelection).toEqual(
  5161. original,
  5162. );
  5163. const sending = service.handleInboundMessage({
  5164. botId: "weixin-1",
  5165. text: "执行这次请求",
  5166. actor: weixinActor,
  5167. });
  5168. if (incomplete) {
  5169. await expect(sending).rejects.toThrow("Submission 模型");
  5170. expect(taskService.createTask).not.toHaveBeenCalled();
  5171. expect((await repo.readState()).bots["weixin-1"]?.draftOptions?.modelSelection).toEqual(
  5172. original,
  5173. );
  5174. } else {
  5175. await sending;
  5176. expect(taskService.createTask).toHaveBeenCalledWith(
  5177. expect.objectContaining({ modelSelection: effective }),
  5178. );
  5179. }
  5180. } finally {
  5181. service.disposeAll();
  5182. }
  5183. },
  5184. );
  5185. it("clears stale providers after a successful empty Model Selection View", async () => {
  5186. const provider = {
  5187. id: "provider-runtime-empty",
  5188. name: "Runtime Provider",
  5189. endpoints: { baseURL: "https://example.com/v1", paths: { "openai-compatible": "" } },
  5190. defaultKind: "openai-compatible" as const,
  5191. apiKey: "key",
  5192. models: ["runtime-model"],
  5193. createdAt: Date.now(),
  5194. updatedAt: Date.now(),
  5195. };
  5196. const modelSelectionService = f.createModelSelectionService([provider]);
  5197. const getView = vi.mocked(modelSelectionService.getView);
  5198. const service = f.createBotsService({
  5199. credentialService: f.createCredentialService({ "weixin-token": "token" }),
  5200. modelSelectionService,
  5201. repo: f.createMemoryRepo(f.weixinConfig) as never,
  5202. });
  5203. const initial = await service.handleInboundMessage({
  5204. botId: "weixin-1",
  5205. text: "/model",
  5206. actor: weixinActor,
  5207. });
  5208. expect(initial[0]?.text).toContain("Runtime Provider");
  5209. getView.mockResolvedValue({
  5210. revision: 2,
  5211. providers: [],
  5212. });
  5213. const empty = await service.handleInboundMessage({
  5214. botId: "weixin-1",
  5215. text: "/model",
  5216. actor: weixinActor,
  5217. });
  5218. expect(empty[0]?.text).toContain("未找到模型供应商");
  5219. expect(empty[0]?.text).not.toContain("Runtime Provider");
  5220. service.disposeAll();
  5221. });
  5222. });