botsService.messageFlow.test.ts 175 KB

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