botsService.groups.test.ts 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588
  1. import { TopicHistoryPermissionError } from "../src/bots/topicHistory.js";
  2. import { afterEach, describe, expect, it, vi } from "vitest";
  3. import type { BotActor, ZCodeStreamEvent } from "@zcode/shared";
  4. import { botsStateFileSchema } from "@zcode/shared";
  5. import * as f from "./botsService.fixtures.js";
  6. const callbackTransport = vi.hoisted(() => ({
  7. enabled: false,
  8. send: vi.fn(async () => ({ providerMessageId: "om_notice" })),
  9. }));
  10. const directoryMock = vi.hoisted(() =>
  11. vi.fn(async (): Promise<Record<string, string>> => ({ ou_user: "Alice" })),
  12. );
  13. const reactionMock = vi.hoisted(() => vi.fn(async () => {}));
  14. const cardCreateMock = vi.hoisted(() =>
  15. vi.fn(async () => ({ providerMessageId: "om_interaction" })),
  16. );
  17. const cardUpdateMock = vi.hoisted(() => vi.fn(async () => {}));
  18. const historyMock = vi.hoisted(() =>
  19. vi.fn(async (_bot: unknown, request: { messageId: string }) => ({
  20. messages: [],
  21. checkpoint: request.messageId,
  22. hasGap: false,
  23. })),
  24. );
  25. vi.mock("../src/bots/providers/feishuProvider.js", async (importOriginal) => {
  26. const actual = await importOriginal<typeof import("../src/bots/providers/feishuProvider.js")>();
  27. return {
  28. ...actual,
  29. createFeishuBotProvider: (...args: Parameters<typeof actual.createFeishuBotProvider>) => ({
  30. ...actual.createFeishuBotProvider(...args),
  31. ...(callbackTransport.enabled
  32. ? {
  33. prepareCallbackPayload: async (_bot: unknown, payload: unknown) => payload,
  34. handleCallbackResponse: undefined,
  35. resolveActorDisplayName: undefined,
  36. acknowledgeCallback: vi.fn(async () => undefined),
  37. send: callbackTransport.send,
  38. }
  39. : {}),
  40. getGroupMemberNames: directoryMock,
  41. readTopicHistory: historyMock,
  42. updateInputReaction: reactionMock,
  43. updateTransientInteractionCard: cardUpdateMock,
  44. createTransientInteractionCard: cardCreateMock,
  45. getGroupInfo: vi.fn(async () => ({ name: "测试群" })),
  46. }),
  47. };
  48. });
  49. const services: Array<ReturnType<typeof f.createBotsService>> = [];
  50. afterEach(async () => {
  51. callbackTransport.enabled = false;
  52. callbackTransport.send.mockClear();
  53. directoryMock.mockClear();
  54. reactionMock.mockClear();
  55. cardUpdateMock.mockClear();
  56. cardCreateMock.mockClear();
  57. historyMock.mockClear();
  58. for (const service of services.splice(0)) await service.disposeAllAndWait();
  59. });
  60. function setup(
  61. uniqueTaskIds = false,
  62. modelUnavailable = false,
  63. remoteConnection?: { connected: boolean },
  64. ) {
  65. const repo = f.createMemoryRepo(structuredClone(f.feishuConfig));
  66. const taskService = f.createLegacyTaskService();
  67. if (uniqueTaskIds) {
  68. // 通用夹具固定返回 task-1,会掩盖跨话题任务校验;隔离用例必须分配不同任务。
  69. const createTask = taskService.createTask;
  70. let taskSequence = 0;
  71. taskService.createTask = vi.fn(async () => ({
  72. ...(await createTask()),
  73. taskId: `topic-task-${++taskSequence}`,
  74. }));
  75. }
  76. taskService.invalidateBotTopicInputs = vi.fn(async () => undefined);
  77. taskService.readBotTopicExecution = vi.fn(async () => undefined);
  78. taskService.stopBotTopicExecution = vi.fn(async () => undefined);
  79. taskService.submitBotGroupInput = vi.fn(async (params) => ({
  80. commandId: params.commandId,
  81. status: "accepted",
  82. revisionAtDecision: 1,
  83. result: { type: "inputAccepted", inputId: params.commandId, delivery: "queue" },
  84. }));
  85. const service = f.createBotsService({
  86. zcodeTaskService: taskService,
  87. repo: repo as never,
  88. credentialService: f.createCredentialService({}),
  89. runStartupBackgroundTasks: false,
  90. ...(remoteConnection
  91. ? {
  92. remoteWorkspaceService: {
  93. isConnected: vi.fn(async () => remoteConnection.connected),
  94. ensureConnected: vi.fn(async () => ({ ok: remoteConnection.connected })),
  95. getZCodeTaskService: vi.fn(async () => taskService),
  96. getModelSelectionService: vi.fn(async () =>
  97. f.createModelSelectionService([{ id: "glm", name: "GLM", models: ["default"] }]),
  98. ),
  99. },
  100. }
  101. : {}),
  102. ...(modelUnavailable
  103. ? { modelSelectionService: { getView: vi.fn(async () => null) } as never }
  104. : {}),
  105. });
  106. services.push(service);
  107. const send = (text: string, chatId = "oc_a", userId = "ou_user", threadId?: string) => {
  108. const actor: BotActor = {
  109. provider: "feishu",
  110. botId: "feishu-1",
  111. chatType: "group",
  112. chatId,
  113. threadId,
  114. ...(threadId ? { rootMessageId: `root_${threadId}`, topicTitle: threadId } : {}),
  115. providerUserId: userId,
  116. providerMessageId: `om_${text}_${userId}`,
  117. };
  118. return service.handleInboundMessage({ botId: actor.botId, actor, text });
  119. };
  120. return { repo, service, send, taskService };
  121. }
  122. describe("Feishu group sessions", () => {
  123. it("keeps other recipients as durable background without stopping or admitting work", async () => {
  124. const { service, send, repo: initialRepo, taskService } = setup();
  125. let repo = initialRepo;
  126. await send("/enable");
  127. await send("start", "oc_a", "ou_user", "omt_roles");
  128. const before = structuredClone(await repo.readState());
  129. const message = {
  130. botId: "feishu-1",
  131. text: "@Other handle the outline",
  132. mentionedBot: false,
  133. botOpenId: "ou_self",
  134. contentParts: [
  135. {
  136. type: "channelMention" as const,
  137. refId: "other",
  138. name: "Feishu",
  139. targetId: "ou_other",
  140. channel: "feishu" as const,
  141. idType: "open_id" as const,
  142. entityType: "unknown" as const,
  143. },
  144. ],
  145. actor: {
  146. provider: "feishu" as const,
  147. botId: "feishu-1",
  148. chatType: "group" as const,
  149. chatId: "oc_a",
  150. threadId: "omt_roles",
  151. rootMessageId: "root_omt_roles",
  152. providerUserId: "ou_user",
  153. providerMessageId: "om_other",
  154. },
  155. };
  156. taskService.submitBotGroupInput.mockClear();
  157. taskService.readBotTopicExecution.mockClear();
  158. historyMock.mockClear();
  159. expect(await service.handleInboundMessage(message)).toEqual([]);
  160. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  161. expect(taskService.readBotTopicExecution).not.toHaveBeenCalled();
  162. expect(historyMock).not.toHaveBeenCalled();
  163. const key = JSON.stringify(["feishu-1", "oc_a", "omt_roles"]);
  164. const saved = (await repo.readState()).bots[key]!.group!;
  165. expect(saved.inputs).toEqual(before.bots[key]!.group!.inputs);
  166. expect(saved.autoReplyGuard).toEqual(before.bots[key]!.group!.autoReplyGuard);
  167. expect(saved.backgroundHistory?.checkpoint).toBe("om_start_ou_user");
  168. // 重建 service 和 repo,确认补读边界不依赖内存。
  169. await service.disposeAllAndWait();
  170. repo = f.createMemoryRepo(
  171. structuredClone(f.feishuConfig),
  172. botsStateFileSchema.parse(JSON.parse(JSON.stringify(await repo.readState()))),
  173. );
  174. const restarted = f.createBotsService({
  175. repo: repo as never,
  176. zcodeTaskService: taskService,
  177. credentialService: f.createCredentialService({}),
  178. runStartupBackgroundTasks: false,
  179. });
  180. services.push(restarted);
  181. await restarted.handleInboundMessage({
  182. ...message,
  183. mentionedBot: true,
  184. actor: { ...message.actor, providerMessageId: "om_both" },
  185. });
  186. expect(historyMock).toHaveBeenCalledWith(
  187. expect.anything(),
  188. expect.objectContaining({ checkpoint: "om_start_ou_user", messageId: "om_both" }),
  189. );
  190. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(1);
  191. expect(taskService.submitBotGroupInput.mock.calls[0]![0].source).toMatchObject({
  192. botIdentity: { name: "Feishu", openId: "ou_self" },
  193. mentionedBot: true,
  194. });
  195. expect((await repo.readState()).bots[key]!.group!.backgroundHistory).toBeUndefined();
  196. await restarted.handleInboundMessage({
  197. ...message,
  198. actor: { ...message.actor, providerMessageId: "om_background_2" },
  199. });
  200. let release!: () => void;
  201. let entered!: () => void;
  202. const waiting = new Promise<void>((resolve) => {
  203. release = resolve;
  204. });
  205. const ready = new Promise<void>((resolve) => {
  206. entered = resolve;
  207. });
  208. historyMock.mockImplementationOnce(async (_bot, request) => {
  209. entered();
  210. await waiting;
  211. return { messages: [], checkpoint: request.messageId, hasGap: false };
  212. });
  213. const accepting = restarted.handleInboundMessage({
  214. ...message,
  215. mentionedBot: true,
  216. actor: { ...message.actor, providerMessageId: "om_accepting" },
  217. });
  218. await ready;
  219. // 补读期间的新背景不能被旧 revision 清除,且保留最早检查点。
  220. await restarted.handleInboundMessage({
  221. ...message,
  222. actor: { ...message.actor, providerMessageId: "om_background_3" },
  223. });
  224. release();
  225. await accepting;
  226. expect((await repo.readState()).bots[key]!.group!.backgroundHistory?.checkpoint).toBe(
  227. "om_both",
  228. );
  229. await restarted.handleInboundMessage({
  230. ...message,
  231. mentionedBot: true,
  232. actor: { ...message.actor, providerMessageId: "om_final" },
  233. });
  234. expect(historyMock).toHaveBeenLastCalledWith(
  235. expect.anything(),
  236. expect.objectContaining({ checkpoint: "om_both", messageId: "om_final" }),
  237. );
  238. expect((await repo.readState()).bots[key]!.group!.backgroundHistory).toBeUndefined();
  239. });
  240. it.each([false, true])(
  241. "keeps empty unmentioned topic output silent (mentioned=%s)",
  242. async (mentionedBot) => {
  243. const { service, send, taskService, repo } = setup();
  244. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  245. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  246. emit = listener;
  247. return { dispose: vi.fn() };
  248. });
  249. await send("/enable");
  250. await send("start", "oc_a", "ou_user", "omt_silent");
  251. await service.handleInboundMessage({
  252. botId: "feishu-1",
  253. mentionedBot,
  254. text: "follow up",
  255. botOpenId: "ou_self",
  256. actor: {
  257. botId: "feishu-1",
  258. provider: "feishu",
  259. chatType: "group",
  260. chatId: "oc_a",
  261. threadId: "omt_silent",
  262. rootMessageId: "root_omt_silent",
  263. providerUserId: "ou_user",
  264. providerMessageId: "om_follow",
  265. },
  266. });
  267. const key = JSON.stringify(["feishu-1", "oc_a", "omt_silent"]);
  268. const context = (await repo.readState()).bots[key]!;
  269. const inputId = Object.keys(context.group!.inputs!).at(-1)!;
  270. const base = { taskId: context.activeTaskId!, inputId, traceId: inputId };
  271. await emit({ ...base, type: "task_run_started", startedAt: 1 });
  272. await emit({ ...base, type: "task_complete", stopReason: "end_turn" });
  273. const deliveries = Object.values((await repo.readState()).bots[key]!.group!.deliveries ?? {});
  274. expect(deliveries).toHaveLength(mentionedBot ? 1 : 0);
  275. if (mentionedBot) expect(deliveries[0]!.text).toMatch(/任务已完成|Task completed/);
  276. },
  277. );
  278. it.each([undefined, "omt_limit"])(
  279. "caps bot turns durably and resets only for new humans (%s)",
  280. async (threadId) => {
  281. const { service, send, repo: initialRepo, taskService } = setup(true);
  282. let repo = initialRepo;
  283. await send("/enable");
  284. await send("start", "oc_a", "ou_user", threadId);
  285. const message = (id: string, senderType: "app" | "user" = "app") => ({
  286. botId: "feishu-1",
  287. senderType,
  288. mentionedBot: true,
  289. text: id,
  290. actor: {
  291. botId: "feishu-1",
  292. provider: "feishu" as const,
  293. chatType: "group" as const,
  294. chatId: "oc_a",
  295. threadId,
  296. rootMessageId: threadId ? `root_${threadId}` : undefined,
  297. providerUserId: senderType === "app" ? "ou_other_bot" : "ou_user",
  298. providerMessageId: id,
  299. },
  300. });
  301. const inputs = async () =>
  302. Object.values((await repo.readState()).bots)
  303. .filter((context) => context.group?.threadId === threadId)
  304. .flatMap((context) => Object.values(context.group?.inputs ?? {}))
  305. .flatMap(
  306. (input) =>
  307. input.source.messages?.map((entry) => entry.messageId) ?? [input.source.messageId],
  308. );
  309. await service.handleInboundMessage(message("bot-0"));
  310. await service.handleInboundMessage(message("bot-0"));
  311. await Promise.all(
  312. Array.from({ length: 8 }, (_, i) => service.handleInboundMessage(message(`bot-${i + 1}`))),
  313. );
  314. expect((await inputs()).filter((id) => id.startsWith("bot-"))).toHaveLength(5);
  315. const calls = taskService.submitBotGroupInput.mock.calls.length;
  316. // 旧真人事件重投不能给自动互答续命。
  317. await send("start", "oc_a", "ou_user", threadId);
  318. await service.handleInboundMessage(message("blocked"));
  319. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(calls);
  320. await service.disposeAllAndWait();
  321. repo = f.createMemoryRepo(
  322. structuredClone(f.feishuConfig),
  323. botsStateFileSchema.parse(JSON.parse(JSON.stringify(await repo.readState()))),
  324. );
  325. const restarted = f.createBotsService({
  326. repo: repo as never,
  327. zcodeTaskService: taskService,
  328. credentialService: f.createCredentialService({}),
  329. runStartupBackgroundTasks: false,
  330. });
  331. services.push(restarted);
  332. await restarted.handleInboundMessage(message("after-restart"));
  333. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(calls);
  334. await restarted.handleInboundMessage(message("human-new", "user"));
  335. await restarted.handleInboundMessage(message("bot-resumed"));
  336. expect(await inputs()).toContain("bot-resumed");
  337. for (let i = 0; i < 4; i++) await restarted.handleInboundMessage(message(`next-${i}`));
  338. await restarted.handleInboundMessage(message("human-new", "user"));
  339. const resumedCalls = taskService.submitBotGroupInput.mock.calls.length;
  340. await restarted.handleInboundMessage(message("blocked-again"));
  341. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(resumedCalls);
  342. // 同群另一个话题使用自己的上限。
  343. await restarted.handleInboundMessage({
  344. ...message("other-human", "user"),
  345. actor: {
  346. ...message("other-human", "user").actor,
  347. threadId: "omt_other",
  348. rootMessageId: "root_other",
  349. },
  350. });
  351. await restarted.handleInboundMessage({
  352. ...message("other-bot"),
  353. actor: {
  354. ...message("other-bot").actor,
  355. threadId: "omt_other",
  356. rootMessageId: "root_other",
  357. },
  358. });
  359. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(resumedCalls + 2);
  360. },
  361. );
  362. it.each(["hello", "/stop", "/reconnect", "/enable"])(
  363. "admits bot main-chat text %s only when enabled and mentioned, never as control",
  364. async (text) => {
  365. const { service, send, taskService } = setup();
  366. const message = {
  367. botId: "feishu-1",
  368. senderType: "app" as const,
  369. mentionedBot: true,
  370. text,
  371. actor: {
  372. botId: "feishu-1",
  373. provider: "feishu" as const,
  374. chatType: "group" as const,
  375. chatId: "oc_a",
  376. providerUserId: "ou_other_bot",
  377. providerMessageId: "om_bot_main",
  378. },
  379. };
  380. expect(await service.handleInboundMessage(message)).toEqual([]);
  381. await send("/enable");
  382. expect(await service.handleInboundMessage({ ...message, mentionedBot: false })).toEqual([]);
  383. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  384. await service.handleInboundMessage(message);
  385. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(1);
  386. },
  387. );
  388. it.each(["/stop", "/reconnect", "/approve permission allow", "hello"])(
  389. "admits other-app text %s only in active topics and never as control",
  390. async (text) => {
  391. const { service, send, taskService, repo } = setup();
  392. await send("/enable");
  393. const message = {
  394. botId: "feishu-1",
  395. senderType: "app" as const,
  396. mentionedBot: true,
  397. text,
  398. actor: {
  399. botId: "feishu-1",
  400. provider: "feishu" as const,
  401. chatType: "group" as const,
  402. chatId: "oc_a",
  403. threadId: "omt_app",
  404. rootMessageId: "root_omt_app",
  405. providerUserId: "ou_other_app",
  406. providerMessageId: "om_app",
  407. },
  408. };
  409. expect(await service.handleInboundMessage(message)).toEqual([]);
  410. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  411. await send("start", "oc_a", "ou_user", "omt_app");
  412. taskService.submitBotGroupInput.mockClear();
  413. await service.handleInboundMessage(message);
  414. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(1);
  415. expect(taskService.submitBotGroupInput.mock.calls[0]?.[0].source).toMatchObject({
  416. messageId: "om_app",
  417. senderId: "ou_other_app",
  418. messages: [expect.objectContaining({ text })],
  419. });
  420. await service.handleInboundMessage(message);
  421. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(1);
  422. await send("/leave", "oc_a", "ou_user", "omt_app");
  423. expect(
  424. await service.handleInboundMessage({
  425. ...message,
  426. actor: { ...message.actor, providerMessageId: "om_after_leave" },
  427. }),
  428. ).toEqual([]);
  429. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(1);
  430. expect(
  431. Object.values((await repo.readState()).bots).find(
  432. (state) => state.group?.threadId === "omt_app",
  433. )?.group?.topicActive,
  434. ).toBe(false);
  435. },
  436. );
  437. it("keeps app reconnect text on the provider callback message path", async () => {
  438. callbackTransport.enabled = true;
  439. const { service, send, taskService } = setup();
  440. await send("/enable");
  441. await send("start", "oc_a", "ou_user", "omt_app");
  442. taskService.submitBotGroupInput.mockClear();
  443. const payload = {
  444. botId: "feishu-1",
  445. zcodeBotOpenId: "ou_current_bot",
  446. event: {
  447. sender: { sender_type: "bot", sender_id: { open_id: "ou_other_bot" } },
  448. message: {
  449. chat_type: "group",
  450. chat_id: "oc_a",
  451. thread_id: "omt_app",
  452. root_id: "root_omt_app",
  453. message_id: "om_app_reconnect",
  454. message_type: "text",
  455. content: JSON.stringify({ text: "/reconnect" }),
  456. },
  457. },
  458. };
  459. await service.handleProviderCallback("feishu", payload);
  460. await service.handleProviderCallback("feishu", payload);
  461. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(1);
  462. expect(taskService.submitBotGroupInput.mock.calls[0]?.[0].source.messages?.[0]?.text).toBe(
  463. "/reconnect",
  464. );
  465. payload.event.sender.sender_id.open_id = "ou_current_bot";
  466. payload.event.message.message_id = "om_self";
  467. await service.handleProviderCallback("feishu", payload);
  468. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(1);
  469. });
  470. it("quotes commands and addresses their sender, not the group owner", async () => {
  471. const { send } = setup();
  472. await send("/enable");
  473. const [reply] = await send("/status", "oc_a", "ou_member");
  474. expect(reply).toMatchObject({
  475. providerUserId: "oc_a",
  476. replyToMessageId: "om_/status_ou_member",
  477. mentionedUserIds: ["ou_member"],
  478. });
  479. });
  480. it.each([false, true])(
  481. "topic command only mentions sender when mentionedBot=%s",
  482. async (mentionedBot) => {
  483. const { send, service } = setup();
  484. await send("/enable");
  485. await send("/status", "oc_a", "ou_member", "omt_reply");
  486. const [reply] = await service.handleInboundMessage({
  487. botId: "feishu-1",
  488. text: "/status",
  489. mentionedBot,
  490. topicRootIsCurrentBot: true,
  491. actor: {
  492. botId: "feishu-1",
  493. provider: "feishu",
  494. chatType: "group",
  495. chatId: "oc_a",
  496. threadId: "omt_reply",
  497. rootMessageId: "root_omt_reply",
  498. providerUserId: "ou_member",
  499. providerMessageId: "om_topic_status",
  500. },
  501. });
  502. expect(reply?.replyToMessageId).toBe("om_topic_status");
  503. expect(reply?.mentionedUserIds).toEqual(mentionedBot ? ["ou_member"] : undefined);
  504. },
  505. );
  506. it("mentions the bound administrator once for owner-only commands in a topic", async () => {
  507. const { send } = setup();
  508. await send("/enable");
  509. const first = await send("/model", "oc_a", "ou_member", "omt_admin");
  510. expect(first[0]).toMatchObject({ mentionedUserIds: ["ou_user"], callbackToastOnly: true });
  511. const repeated = await send("/model", "oc_a", "ou_other", "omt_admin");
  512. expect(repeated[0]?.mentionedUserIds).toEqual([]);
  513. const otherTopic = await send("/model", "oc_a", "ou_member", "omt_other");
  514. expect(otherTopic[0]?.mentionedUserIds).toEqual(["ou_user"]);
  515. });
  516. it("mentions the administrator when the group has not been enabled", async () => {
  517. const { send } = setup();
  518. expect((await send("hello", "oc_a", "ou_member"))[0]?.mentionedUserIds).toEqual(["ou_user"]);
  519. });
  520. it("mentions the administrator on model resolution failures without alerting for general failures", async () => {
  521. const { send, taskService } = setup(false, true);
  522. await send("/enable");
  523. const replies = await send("hello", "oc_a", "ou_member", "omt_model");
  524. expect(replies[0]?.text).toContain("Submission");
  525. expect(replies[0]?.mentionedUserIds).toEqual(["ou_user"]);
  526. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  527. expect((await send("retry", "oc_a", "ou_other", "omt_model"))[0]?.mentionedUserIds).toEqual([]);
  528. });
  529. it.each([false, true])(
  530. "only plan approval mentions the administrator (plan=%s)",
  531. async (plan) => {
  532. const { send, taskService } = setup();
  533. let listener!: (event: ZCodeStreamEvent) => Promise<void>;
  534. taskService.onDynamicTaskEvent = vi.fn(() => (next: typeof listener) => {
  535. listener = next;
  536. return { dispose() {} };
  537. }) as never;
  538. await send("/enable");
  539. await send("start", "oc_a", "ou_member", "omt_question");
  540. const event = {
  541. type: "elicitation_request",
  542. taskId: "task-1",
  543. traceId: "run-question",
  544. requestId: "question-1",
  545. message: "Choose",
  546. options: [{ value: "approve", label: "Approve" }],
  547. ...(plan ? { schema: { interaction: "plan_approval", plan: "Build the board" } } : {}),
  548. } as ZCodeStreamEvent;
  549. await listener(event);
  550. const first = cardCreateMock.mock.calls.at(-1) as unknown as [
  551. unknown,
  552. { mentionedUserIds?: string[] },
  553. ];
  554. expect(first[1].mentionedUserIds).toEqual(plan ? ["ou_user"] : undefined);
  555. await listener(event);
  556. expect(cardCreateMock).toHaveBeenCalledTimes(1);
  557. const updated = cardUpdateMock.mock.calls.at(-1) as unknown as [
  558. unknown,
  559. unknown,
  560. { mentionedUserIds?: string[] },
  561. ];
  562. expect(updated[2].mentionedUserIds).toEqual(plan ? [] : undefined);
  563. },
  564. );
  565. it("alerts once while remote workspace is disconnected and re-arms after recovery", async () => {
  566. const connection = { connected: true };
  567. const { send } = setup(false, false, connection);
  568. await send("/enable");
  569. connection.connected = false;
  570. expect((await send("hello", "oc_a", "ou_member"))[0]?.mentionedUserIds).toEqual(["ou_user"]);
  571. expect((await send("again", "oc_a", "ou_other"))[0]?.mentionedUserIds).toEqual([]);
  572. connection.connected = true;
  573. await send("start", "oc_a", "ou_member");
  574. connection.connected = false;
  575. expect((await send("retry", "oc_a", "ou_member"))[0]?.mentionedUserIds).toEqual(["ou_user"]);
  576. });
  577. it("does not notify the administrator for general topic preparation errors", async () => {
  578. const { send, taskService } = setup();
  579. await send("/enable");
  580. taskService.createTask.mockRejectedValueOnce(new Error("General task error"));
  581. const reply = (await send("hello", "oc_a", "ou_member", "omt_error"))[0];
  582. expect(reply?.text).toContain("General task error");
  583. expect(reply?.administratorAttention).not.toBe(true);
  584. expect(reply?.mentionedUserIds).toBeUndefined();
  585. });
  586. it("sends a separate administrator notice for a denied card without modifying the shared card", async () => {
  587. callbackTransport.enabled = true;
  588. const { send, service, taskService } = setup();
  589. let listener!: (event: ZCodeStreamEvent) => Promise<void>;
  590. taskService.onDynamicTaskEvent = vi.fn(() => (next: typeof listener) => {
  591. listener = next;
  592. return { dispose() {} };
  593. }) as never;
  594. await send("/enable");
  595. await send("start", "oc_a", "ou_member");
  596. const permission = {
  597. type: "permission_request",
  598. taskId: "task-1",
  599. traceId: "run-card",
  600. requestId: "permission-card",
  601. description: "Read file",
  602. kind: "read",
  603. raw: {},
  604. options: [
  605. { optionId: "allow", name: "Allow", kind: "allow_once", response: { decision: "allow" } },
  606. ],
  607. } as ZCodeStreamEvent;
  608. await listener(permission);
  609. const state = (await service.getBotStates()).find((entry) => entry.group?.chatId === "oc_a")!;
  610. const payload = (eventId: string) => ({
  611. botId: "feishu-1",
  612. event_type: "card.action.trigger",
  613. event_id: eventId,
  614. operator: { operator_id: { open_id: "ou_member" } },
  615. action: {
  616. value: {
  617. command: "/model",
  618. groupCard: {
  619. chatId: "oc_a",
  620. taskId: state.activeTaskId!,
  621. authorizationId: state.group!.authorizationId,
  622. },
  623. },
  624. },
  625. context: { chat_type: "group_chat", open_chat_id: "oc_a", open_message_id: "om_card" },
  626. });
  627. await service.handleProviderCallbackResponse("feishu", payload("click-1"));
  628. expect(callbackTransport.send).toHaveBeenCalledTimes(1);
  629. expect(callbackTransport.send).toHaveBeenLastCalledWith(
  630. expect.anything(),
  631. expect.objectContaining({ mentionedUserIds: ["ou_user"], callbackToastOnly: undefined }),
  632. );
  633. expect(cardUpdateMock).not.toHaveBeenCalled();
  634. await service.handleProviderCallbackResponse("feishu", payload("click-2"));
  635. expect(callbackTransport.send).toHaveBeenCalledTimes(1);
  636. expect(cardUpdateMock).not.toHaveBeenCalled();
  637. await listener(permission);
  638. expect(cardCreateMock).toHaveBeenCalledTimes(1);
  639. expect(cardUpdateMock).toHaveBeenCalledTimes(1);
  640. });
  641. it("automatically joins a verified bot-rooted topic without a mention", async () => {
  642. const { send, service, taskService } = setup();
  643. await send("/enable");
  644. await service.handleInboundMessage({
  645. botId: "feishu-1",
  646. text: "continue",
  647. mentionedBot: false,
  648. topicRootIsCurrentBot: true,
  649. actor: {
  650. botId: "feishu-1",
  651. provider: "feishu",
  652. chatType: "group",
  653. chatId: "oc_a",
  654. threadId: "bot-root",
  655. rootMessageId: "root",
  656. topicTitle: "Bot reply",
  657. providerUserId: "ou_user",
  658. providerMessageId: "incoming",
  659. },
  660. referencedMessage: { messageId: "root", text: "Bot reply" },
  661. });
  662. expect(taskService.createTask).toHaveBeenCalledOnce();
  663. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  664. });
  665. it("leaves the topic without losing its task and requires a new mention to resume", async () => {
  666. const { send, service, taskService } = setup();
  667. await send("/enable");
  668. await send("start", "oc_a", "ou_user", "omt_active");
  669. await send("/leave", "oc_a", "ou_user", "omt_active");
  670. const topic = (await service.getBotStates()).find(
  671. (state) => state.group?.threadId === "omt_active",
  672. );
  673. expect(topic?.group?.topicActive).toBe(false);
  674. await service.handleInboundMessage({
  675. botId: "feishu-1",
  676. text: "ignored",
  677. mentionedBot: false,
  678. topicRootIsCurrentBot: true,
  679. actor: {
  680. botId: "feishu-1",
  681. provider: "feishu",
  682. chatType: "group",
  683. chatId: "oc_a",
  684. threadId: "omt_active",
  685. providerUserId: "ou_user",
  686. providerMessageId: "ignored",
  687. },
  688. });
  689. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  690. await send("resume", "oc_a", "ou_user", "omt_active");
  691. expect(taskService.createTask).toHaveBeenCalledOnce();
  692. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  693. expect(
  694. (await service.getBotStates()).find((state) => state.group?.threadId === "omt_active")?.group
  695. ?.topicActive,
  696. ).toBe(true);
  697. });
  698. it.each(["/stop", "/history off", "/disable"])(
  699. "cancels a pending topic batch when %s arrives during history preparation",
  700. async (command) => {
  701. const { send, taskService, service } = setup();
  702. await send("/enable");
  703. await send("start", "oc_a", "ou_user", "omt_active");
  704. await send("/history on");
  705. let release!: () => void;
  706. historyMock.mockImplementationOnce(async (bot, request) => {
  707. await new Promise<void>((resolve) => {
  708. release = resolve;
  709. });
  710. return { messages: [], checkpoint: request.messageId, hasGap: false };
  711. });
  712. reactionMock.mockClear();
  713. const pending = send("pending", "oc_a", "ou_user", "omt_active");
  714. await vi.waitFor(() => expect(release).toBeTypeOf("function"));
  715. expect((reactionMock.mock.lastCall as unknown[] | undefined)?.[2]).toBe("waiting");
  716. expect(
  717. (await service.getBotStates()).find((state) => state.group?.threadId === "omt_active"),
  718. ).toMatchObject({
  719. group: { preparation: [expect.objectContaining({ text: "pending", status: "preparing" })] },
  720. });
  721. await send(command, "oc_a", "ou_user", "omt_active");
  722. expect(
  723. (await service.getBotStates()).find((state) => state.group?.threadId === "omt_active"),
  724. ).toMatchObject({ group: { preparation: [] } });
  725. release();
  726. await pending;
  727. await new Promise((resolve) => setTimeout(resolve, 0));
  728. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  729. expect((reactionMock.mock.lastCall as unknown[] | undefined)?.[2]).toBe("cancelled");
  730. },
  731. );
  732. it("cancels history preparation in sibling topics from the group history switch", async () => {
  733. const { send, taskService } = setup();
  734. await send("/enable");
  735. const releases: Array<() => void> = [];
  736. const prepare: typeof historyMock = vi.fn(async (_bot, request) => {
  737. await new Promise<void>((resolve) => releases.push(resolve));
  738. return { messages: [], checkpoint: request.messageId, hasGap: false };
  739. });
  740. historyMock.mockImplementationOnce(prepare).mockImplementationOnce(prepare);
  741. const a = send("first topic", "oc_a", "ou_user", "omt_a");
  742. const b = send("second topic", "oc_a", "ou_user", "omt_b");
  743. await vi.waitFor(() => expect(releases).toHaveLength(2));
  744. await send("/history off");
  745. releases.forEach((release) => release());
  746. expect(await Promise.all([a, b])).toEqual([[], []]);
  747. await new Promise((resolve) => setTimeout(resolve, 0));
  748. expect(taskService.createTask).not.toHaveBeenCalled();
  749. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  750. });
  751. it("does not submit prepared topic material after service disposal", async () => {
  752. const { send, service, taskService } = setup();
  753. await send("/enable");
  754. let release!: () => void;
  755. historyMock.mockImplementationOnce(async (_bot, request) => {
  756. await new Promise<void>((resolve) => {
  757. release = resolve;
  758. });
  759. return { messages: [], checkpoint: request.messageId, hasGap: false };
  760. });
  761. const pending = send("shutdown material", "oc_a", "ou_user", "omt_shutdown");
  762. await vi.waitFor(() => expect(release).toBeTypeOf("function"));
  763. await service.disposeAllAndWait();
  764. release();
  765. expect(await pending).toEqual([]);
  766. await new Promise((resolve) => setTimeout(resolve, 0));
  767. expect(taskService.createTask).not.toHaveBeenCalled();
  768. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  769. });
  770. it("cancels topic preparation when the binding user changes", async () => {
  771. const { send, service, taskService, repo } = setup();
  772. await send("/enable");
  773. let release!: () => void;
  774. historyMock.mockImplementationOnce(async (_bot, request) => {
  775. await new Promise<void>((resolve) => {
  776. release = resolve;
  777. });
  778. return { messages: [], checkpoint: request.messageId, hasGap: false };
  779. });
  780. const pending = send("binding material", "oc_a", "ou_user", "omt_binding");
  781. await vi.waitFor(() => expect(release).toBeTypeOf("function"));
  782. const config = await repo.readConfig();
  783. config.bots[0]!.providerUserId = "new-owner";
  784. await service.saveConfig(config);
  785. release();
  786. expect(await pending).toEqual([]);
  787. await new Promise((resolve) => setTimeout(resolve, 0));
  788. expect(taskService.createTask).not.toHaveBeenCalled();
  789. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  790. });
  791. it("retries failed preparation only in its bound task and workspace", async () => {
  792. const { send, service, repo, taskService } = setup();
  793. await send("/enable");
  794. await send("start", "oc_a", "ou_user", "omt_retry");
  795. await send("/history on");
  796. historyMock.mockRejectedValueOnce(new Error("temporary history error"));
  797. await send("retry material", "oc_a", "ou_user", "omt_retry");
  798. const context = (await service.getBotStates()).find(
  799. (value) => value.group?.threadId === "omt_retry",
  800. )!;
  801. const params = {
  802. botId: context.botId,
  803. chatId: "oc_a",
  804. threadId: "omt_retry",
  805. taskId: context.activeTaskId!,
  806. workspacePath: context.workspacePath,
  807. workspaceIdentity: context.workspaceIdentity,
  808. messageId: context.group!.preparation![0]!.messageId,
  809. };
  810. await expect(
  811. service.retryTopicPreparation!({ ...params, taskId: "other-task" }),
  812. ).rejects.toThrow();
  813. await expect(
  814. service.retryTopicPreparation!({ ...params, workspaceIdentity: "another-workspace" }),
  815. ).rejects.toThrow("workspace changed");
  816. const key = JSON.stringify([params.botId, params.chatId, params.threadId]);
  817. for (const admission of ["pending", "accepted", "rejected"] as const) {
  818. const saved = await repo.readState();
  819. saved.bots[key]!.group!.inputs!.recorded = {
  820. taskId: params.taskId,
  821. admission,
  822. source: {
  823. ...Object.values(context.group!.inputs!)[0]!.source,
  824. messageId: params.messageId,
  825. messages: undefined,
  826. },
  827. };
  828. await repo.writeState(saved);
  829. await expect(service.retryTopicPreparation!(params)).rejects.toThrow("already submitted");
  830. expect(
  831. (await service.getBotStates()).find((value) => value.group?.threadId === params.threadId)!
  832. .group!.preparation![0]!.status,
  833. ).toBe("failed");
  834. }
  835. const saved = await repo.readState();
  836. delete saved.bots[key]!.group!.inputs!.recorded;
  837. await repo.writeState(saved);
  838. await service.retryTopicPreparation!(params);
  839. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  840. expect(
  841. (await service.getBotStates()).find((value) => value.group?.threadId === "omt_retry")!.group!
  842. .preparation,
  843. ).toEqual([]);
  844. expect(
  845. Object.values((await repo.readState()).bots).find(
  846. (value) => value.group?.threadId === "omt_retry",
  847. )!.group,
  848. ).not.toHaveProperty("preparation");
  849. });
  850. it("does not stop a running topic for an already accepted message", async () => {
  851. const { send, taskService } = setup();
  852. await send("/enable");
  853. await send("start", "oc_a", "ou_user", "omt_active");
  854. await new Promise((resolve) => setTimeout(resolve, 0));
  855. vi.mocked(taskService.readBotTopicExecution!).mockResolvedValue({ executionId: "running" });
  856. await send("start", "oc_a", "ou_user", "omt_active");
  857. expect(taskService.stopBotTopicExecution).not.toHaveBeenCalled();
  858. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  859. });
  860. it("admits meaningful batch content when its last message is only a native wakeup", async () => {
  861. const { send, service, taskService } = setup();
  862. await send("/enable");
  863. await send("start", "oc_a", "ou_user", "omt_active");
  864. vi.mocked(taskService.readBotTopicExecution!).mockResolvedValue({ executionId: "old" });
  865. const started = Promise.withResolvers<void>();
  866. const released = Promise.withResolvers<void>();
  867. vi.mocked(taskService.stopBotTopicExecution!).mockImplementation(async () => {
  868. started.resolve();
  869. await released.promise;
  870. });
  871. const actor = {
  872. provider: "feishu" as const,
  873. botId: "feishu-1",
  874. chatType: "group" as const,
  875. chatId: "oc_a",
  876. threadId: "omt_active",
  877. rootMessageId: "root_omt_active",
  878. providerUserId: "ou_user",
  879. };
  880. const first = service.handleInboundMessage({
  881. botId: "feishu-1",
  882. actor: { ...actor, providerMessageId: "om_requirement" },
  883. text: "@Bot analyze logs",
  884. commandText: "analyze logs",
  885. mentionedBot: true,
  886. });
  887. await started.promise;
  888. const last = service.handleInboundMessage({
  889. botId: "feishu-1",
  890. actor: { ...actor, providerMessageId: "om_wakeup" },
  891. text: "@Bot",
  892. commandText: "",
  893. mentionedBot: true,
  894. });
  895. await vi.waitFor(async () =>
  896. expect(
  897. (await service.getBotStates()).find((s) => s.group?.threadId === "omt_active")?.group
  898. ?.preparation?.length,
  899. ).toBe(2),
  900. );
  901. released.resolve();
  902. await Promise.all([first, last]);
  903. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  904. expect(
  905. vi
  906. .mocked(taskService.submitBotGroupInput!)
  907. .mock.calls.at(-1)?.[0]
  908. .source.messages?.map((m) => m.text),
  909. ).toEqual(["@Bot analyze logs", "@Bot"]);
  910. });
  911. it("stops the old topic run and submits all intervening messages together", async () => {
  912. const { send, taskService, repo } = setup();
  913. await send("/enable");
  914. await send("start", "oc_a", "ou_user", "omt_active");
  915. const firstCommand = vi.mocked(taskService.submitBotGroupInput!).mock.calls[0]![0].commandId;
  916. vi.mocked(taskService.readBotTopicExecution!).mockResolvedValue({
  917. executionId: "old",
  918. sourceCommandId: firstCommand,
  919. });
  920. let finish!: () => void;
  921. vi.mocked(taskService.stopBotTopicExecution!).mockImplementation(
  922. () =>
  923. new Promise((resolve) => {
  924. finish = resolve;
  925. }),
  926. );
  927. const b = send("second", "oc_a", "ou_user", "omt_active");
  928. await vi.waitFor(() => expect(taskService.stopBotTopicExecution).toHaveBeenCalledOnce());
  929. const c = send("third", "oc_a", "ou_user", "omt_active");
  930. await new Promise((resolve) => setTimeout(resolve, 10));
  931. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(1);
  932. finish();
  933. await Promise.all([b, c]);
  934. expect(
  935. (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a", "omt_active"])]!.group!
  936. .inputs![firstCommand]!.progress,
  937. ).toMatchObject({ status: "stopped", interruptionReason: "newMessage" });
  938. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  939. expect(
  940. vi
  941. .mocked(taskService.submitBotGroupInput!)
  942. .mock.calls.at(-1)?.[0]
  943. .source.messages?.map((m) => m.text),
  944. ).toEqual(["second", "third"]);
  945. const originals = vi.mocked(taskService.submitBotGroupInput!).mock.calls.at(-1)![0]
  946. .source.messages!;
  947. for (const original of originals) {
  948. expect(
  949. reactionMock.mock.calls.some((call) => (call as unknown[])[1] === original.messageId),
  950. ).toBe(true);
  951. }
  952. });
  953. it("does not reinject a root quote prepared before the previous input was accepted", async () => {
  954. const { service, send, taskService } = setup();
  955. await send("/enable");
  956. const submit = (id: string) =>
  957. service.handleInboundMessage({
  958. botId: "feishu-1",
  959. text: id,
  960. mentionedBot: true,
  961. attachments: [
  962. {
  963. id: "root-file",
  964. kind: "file",
  965. filename: "root.txt",
  966. mimeType: "text/plain",
  967. dataBase64: "dGVzdA==",
  968. providerMetadata: { resourceMessageId: "root" },
  969. },
  970. {
  971. id,
  972. kind: "file",
  973. filename: `${id}.txt`,
  974. mimeType: "text/plain",
  975. dataBase64: "dGVzdA==",
  976. providerMetadata: { resourceMessageId: id },
  977. },
  978. ],
  979. referencedMessage: { messageId: "root", text: "shared root" },
  980. actor: {
  981. botId: "feishu-1",
  982. provider: "feishu",
  983. chatType: "group",
  984. chatId: "oc_a",
  985. threadId: "omt_root",
  986. rootMessageId: "root",
  987. providerUserId: "ou_user",
  988. providerMessageId: id,
  989. },
  990. });
  991. await submit("first");
  992. await submit("second");
  993. const calls = vi.mocked(taskService.submitBotGroupInput!).mock.calls;
  994. expect(calls[0]![0].conversationQuotes).toHaveLength(1);
  995. expect(calls[1]![0].conversationQuotes).toEqual([]);
  996. expect(calls[0]![0].attachments?.map((item) => item.filename)).toContain("root.txt");
  997. expect(calls[1]![0].attachments?.map((item) => item.filename)).toEqual(["second.txt"]);
  998. expect(calls[1]![0].source.messages![0]!.attachmentIndexes).toEqual([0]);
  999. expect(calls[1]![0].source.messages![0]!.conversationQuotes ?? []).toEqual([]);
  1000. });
  1001. it("keeps consecutive topic replies separate on the same continuous subscription", async () => {
  1002. const { send, taskService, repo } = setup();
  1003. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1004. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1005. emit = listener;
  1006. return { dispose: vi.fn() };
  1007. });
  1008. await send("/enable");
  1009. const key = JSON.stringify(["feishu-1", "oc_a", "omt_replies"]);
  1010. const replies = ["这是一张图标图片。", "你好!我在的~"];
  1011. for (const [index, reply] of replies.entries()) {
  1012. await send(`request-${index}`, "oc_a", "ou_user", "omt_replies");
  1013. const context = (await repo.readState()).bots[key]!;
  1014. const inputId = Object.keys(context.group!.inputs!).at(-1)!;
  1015. const base = { taskId: context.activeTaskId!, inputId, traceId: inputId };
  1016. await emit({ ...base, type: "task_run_started", startedAt: index + 1 });
  1017. await emit({ ...base, type: "agent_message_chunk", content: reply });
  1018. await emit({ ...base, type: "task_complete", stopReason: "end_turn" });
  1019. const deliveries = Object.values((await repo.readState()).bots[key]!.group!.deliveries!);
  1020. expect(deliveries.map((item) => item.text)).toEqual(replies.slice(0, index + 1));
  1021. expect(deliveries.at(-1)?.replyToMessageId).toBe(`om_request-${index}_ou_user`);
  1022. }
  1023. expect(taskService.onDynamicTaskEvent).toHaveBeenCalledOnce();
  1024. expect(taskService.onDynamicTaskEvent).toHaveBeenCalledWith(
  1025. expect.objectContaining({ deliveryKind: "bot-channel-continuous" }),
  1026. );
  1027. });
  1028. it("ignores a late terminal event from the previous topic input", async () => {
  1029. const { send, taskService, repo } = setup();
  1030. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1031. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1032. emit = listener;
  1033. return { dispose: vi.fn() };
  1034. });
  1035. await send("/enable");
  1036. await send("first", "oc_a", "ou_user", "omt_late");
  1037. await send("second", "oc_a", "ou_user", "omt_late");
  1038. const context = (await repo.readState()).bots[
  1039. JSON.stringify(["feishu-1", "oc_a", "omt_late"])
  1040. ]!;
  1041. const [first, second] = Object.keys(context.group!.inputs!);
  1042. await emit({
  1043. type: "task_run_started",
  1044. taskId: context.activeTaskId!,
  1045. inputId: second,
  1046. } as Parameters<typeof emit>[0]);
  1047. expect(
  1048. (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a", "omt_late"])]!.group!
  1049. .inputs![second!]!.progress?.status,
  1050. ).toBe("working");
  1051. reactionMock.mockClear();
  1052. await emit({
  1053. type: "task_complete",
  1054. taskId: context.activeTaskId!,
  1055. inputId: first,
  1056. stopReason: "end_turn",
  1057. } as Parameters<typeof emit>[0]);
  1058. expect(reactionMock).not.toHaveBeenCalled();
  1059. });
  1060. it("ignores unjoined discussion and accepts non-mention messages after topic admission", async () => {
  1061. const { service, send, taskService } = setup();
  1062. await send("/enable");
  1063. const discussion = (text: string) =>
  1064. service.handleInboundMessage({
  1065. botId: "feishu-1",
  1066. text,
  1067. mentionedBot: false,
  1068. actor: {
  1069. botId: "feishu-1",
  1070. provider: "feishu",
  1071. chatType: "group",
  1072. chatId: "oc_a",
  1073. threadId: "omt_active",
  1074. rootMessageId: "root_omt_active",
  1075. providerUserId: "ou_user",
  1076. providerMessageId: `om_${text}`,
  1077. },
  1078. });
  1079. expect(await discussion("before")).toEqual([]);
  1080. expect(taskService.createTask).not.toHaveBeenCalled();
  1081. await send("start", "oc_a", "ou_user", "omt_active");
  1082. await discussion("after");
  1083. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  1084. expect(
  1085. (await service.getBotStates()).find((s) => s.group?.threadId === "omt_active")?.group
  1086. ?.topicActive,
  1087. ).toBe(true);
  1088. });
  1089. it.each(["feishu", "lark"] as const)(
  1090. "includes permission setup links when enabling %s",
  1091. async (provider) => {
  1092. const { repo, service } = setup();
  1093. const config = await repo.readConfig();
  1094. config.bots[0]!.provider = provider;
  1095. await repo.writeConfig(config);
  1096. const enable = () =>
  1097. service.handleInboundMessage({
  1098. botId: "feishu-1",
  1099. text: "/enable",
  1100. actor: {
  1101. botId: "feishu-1",
  1102. provider,
  1103. chatType: "group",
  1104. chatId: "oc_a",
  1105. providerUserId: "ou_user",
  1106. },
  1107. });
  1108. for (let attempt = 0; attempt < 2; attempt++) {
  1109. const replies = await enable();
  1110. expect(replies[0]?.text).toContain(
  1111. provider === "lark" ? "https://open.larksuite.com/app" : "https://open.feishu.cn/app",
  1112. );
  1113. expect(replies[0]?.text).toContain("im:message.group_msg");
  1114. expect(replies[0]?.mentionedUserIds).toBeUndefined();
  1115. expect(replies[0]?.text).toContain("im:chat.members:read");
  1116. expect(replies[0]?.text).toContain("缺少此权限不影响任务执行");
  1117. expect(replies[0]?.text).toContain("发布");
  1118. }
  1119. },
  1120. );
  1121. it("retains topic authorization on transient permission cards", async () => {
  1122. const { send, taskService, service } = setup();
  1123. let listener: ((event: ZCodeStreamEvent) => Promise<void> | void) | undefined;
  1124. taskService.onDynamicTaskEvent = vi.fn(() => (next: typeof listener) => {
  1125. listener = next;
  1126. return { dispose() {} };
  1127. }) as never;
  1128. await send("/enable");
  1129. await send("read attachment", "oc_a", "member", "omt_a");
  1130. await listener!({
  1131. type: "permission_request",
  1132. taskId: "task-1",
  1133. traceId: "run-a",
  1134. requestId: "permission-a",
  1135. description: "Read historical file",
  1136. kind: "read",
  1137. raw: {},
  1138. options: [
  1139. { optionId: "allow", name: "Allow", kind: "allow_once", response: { decision: "allow" } },
  1140. ],
  1141. } as ZCodeStreamEvent);
  1142. const topic = (await service.getBotStates()).find(
  1143. (state) => state.group?.threadId === "omt_a",
  1144. )!;
  1145. expect(cardCreateMock).toHaveBeenCalledWith(
  1146. expect.anything(),
  1147. expect.objectContaining({
  1148. threadId: "omt_a",
  1149. rootMessageId: "root_omt_a",
  1150. mentionedUserIds: ["ou_user"],
  1151. groupTaskId: "task-1",
  1152. groupCard: expect.objectContaining({
  1153. chatId: "oc_a",
  1154. threadId: "omt_a",
  1155. taskId: "task-1",
  1156. authorizationId: topic.group!.authorizationId,
  1157. }),
  1158. }),
  1159. );
  1160. });
  1161. it("guides an empty main-chat mention without admission or reactions", async () => {
  1162. const { send, taskService } = setup();
  1163. await send("/enable");
  1164. const reply = await send("");
  1165. expect(reply[0]?.text).toContain("补充需求");
  1166. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1167. expect(reactionMock).not.toHaveBeenCalled();
  1168. });
  1169. it("does not execute a bare topic mention without history opt-in", async () => {
  1170. const { send, taskService } = setup();
  1171. await send("/enable");
  1172. expect((await send("", "oc_a", "ou_user", "omt_empty"))[0]?.text).toContain("补充需求");
  1173. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1174. });
  1175. it("submits explicitly quoted control text as a single ordinary input", async () => {
  1176. const { send, service, taskService } = setup();
  1177. await send("/enable");
  1178. await service.handleInboundMessage({
  1179. botId: "feishu-1",
  1180. text: "",
  1181. referencedMessage: { messageId: "om_question", text: "/stop" },
  1182. actor: {
  1183. botId: "feishu-1",
  1184. provider: "feishu",
  1185. chatType: "group",
  1186. chatId: "oc_a",
  1187. providerUserId: "ou_user",
  1188. providerMessageId: "om_quote_request",
  1189. },
  1190. });
  1191. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1192. const submitted = taskService.submitBotGroupInput.mock.calls[0]![0];
  1193. expect(submitted.content).toBe("");
  1194. expect(submitted.conversationQuotes).toEqual([{ messageId: "om_question", text: "/stop" }]);
  1195. expect(submitted.content).not.toContain("[Quoted message]");
  1196. expect(submitted.content).not.toContain("om_question");
  1197. });
  1198. it("keeps quoted text separate from real file and image attachments", async () => {
  1199. const { send, service, taskService } = setup();
  1200. await send("/enable");
  1201. await service.handleInboundMessage({
  1202. botId: "feishu-1",
  1203. text: "inspect these",
  1204. referencedMessage: { messageId: "om_quote_file", text: "original line\nsecond line" },
  1205. attachments: [
  1206. {
  1207. id: "file",
  1208. kind: "file",
  1209. filename: "reference.txt",
  1210. mimeType: "text/plain",
  1211. sizeBytes: 4,
  1212. dataBase64: "dGVzdA==",
  1213. },
  1214. {
  1215. id: "image",
  1216. kind: "image",
  1217. filename: "reference.png",
  1218. mimeType: "image/png",
  1219. sizeBytes: 4,
  1220. dataBase64: "dGVzdA==",
  1221. },
  1222. ],
  1223. actor: {
  1224. botId: "feishu-1",
  1225. provider: "feishu",
  1226. chatType: "group",
  1227. chatId: "oc_a",
  1228. providerUserId: "ou_user",
  1229. providerMessageId: "om_quote_with_materials",
  1230. },
  1231. });
  1232. const admitted = taskService.submitBotGroupInput.mock.calls[0]![0];
  1233. expect(admitted.content).toBe("inspect these");
  1234. expect(admitted.conversationQuotes).toEqual([
  1235. expect.objectContaining({ text: "original line\nsecond line" }),
  1236. ]);
  1237. expect(admitted.attachments).toEqual([
  1238. expect.objectContaining({ kind: "file", filename: "reference.txt", dataBase64: "dGVzdA==" }),
  1239. expect.objectContaining({ kind: "image", filename: "reference.png", dataBase64: "dGVzdA==" }),
  1240. ]);
  1241. });
  1242. it.each([1, 5])(
  1243. "rejects unavailable or excessive group attachments atomically (%s)",
  1244. async (count) => {
  1245. const { send, service, taskService } = setup();
  1246. await send("/enable");
  1247. await service.handleInboundMessage({
  1248. botId: "feishu-1",
  1249. text: "do not execute incomplete input",
  1250. attachments: Array.from({ length: count }, (_, i) => ({
  1251. id: `file-${i}`,
  1252. kind: "file" as const,
  1253. filename: "missing.txt",
  1254. mimeType: "text/plain",
  1255. sizeBytes: 4,
  1256. ...(count > 1 ? { dataBase64: "dGVzdA==" } : {}),
  1257. })),
  1258. actor: {
  1259. botId: "feishu-1",
  1260. provider: "feishu",
  1261. chatType: "group",
  1262. chatId: "oc_a",
  1263. providerUserId: "ou_user",
  1264. providerMessageId: `om_missing_${count}`,
  1265. },
  1266. });
  1267. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1268. expect(taskService.createTask).not.toHaveBeenCalled();
  1269. },
  1270. );
  1271. it("rejects oversized explicit quotations before creating or admitting a task", async () => {
  1272. const { send, service, taskService } = setup();
  1273. await send("/enable");
  1274. const replies = await service.handleInboundMessage({
  1275. botId: "feishu-1",
  1276. text: "summarize",
  1277. referencedMessage: { messageId: "om_large_quote", text: "a".repeat(8001) },
  1278. actor: {
  1279. botId: "feishu-1",
  1280. provider: "feishu",
  1281. chatType: "group",
  1282. chatId: "oc_a",
  1283. providerUserId: "ou_user",
  1284. providerMessageId: "om_large_request",
  1285. },
  1286. });
  1287. expect(replies.length).toBeGreaterThan(0);
  1288. expect(taskService.createTask).not.toHaveBeenCalled();
  1289. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1290. });
  1291. it("blocks explicitly disabled history before task creation", async () => {
  1292. const { send, taskService } = setup();
  1293. await send("/enable");
  1294. await send("/history off");
  1295. const replies = await send("hello", "oc_a", "ou_user", "omt_off");
  1296. expect(historyMock).not.toHaveBeenCalled();
  1297. expect(taskService.createTask).not.toHaveBeenCalled();
  1298. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1299. expect(replies[0]?.text).toContain("/history on");
  1300. expect(replies[0]?.mentionedUserIds).toEqual(["ou_user"]);
  1301. });
  1302. it("guides the administrator without admission on missing history permission", async () => {
  1303. const { send, taskService } = setup();
  1304. await send("/enable");
  1305. historyMock.mockRejectedValueOnce(new TopicHistoryPermissionError("Access denied"));
  1306. const replies = await send("hello", "oc_a", "ou_user", "omt_permission");
  1307. expect(replies[0]?.text).toContain("im:message.group_msg");
  1308. expect(replies[0]?.text).toContain("https://open.feishu.cn/app");
  1309. expect(taskService.createTask).not.toHaveBeenCalled();
  1310. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1311. await send("retry", "oc_a", "ou_user", "omt_permission");
  1312. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1313. });
  1314. it("reads topic history by default and blocks a failed read before task creation", async () => {
  1315. const { send, taskService } = setup();
  1316. await send("/enable");
  1317. historyMock.mockRejectedValueOnce(new Error("network unavailable"));
  1318. const replies = await send("hello", "oc_a", "ou_user", "omt_error");
  1319. expect(historyMock).toHaveBeenCalledOnce();
  1320. expect(taskService.createTask).not.toHaveBeenCalled();
  1321. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1322. expect(replies[0]?.text).toMatch(/retry|重试/);
  1323. expect((reactionMock.mock.lastCall as unknown[] | undefined)?.[2]).toBe("failed");
  1324. });
  1325. it("uses available opted-in topic discussion for a bare mention", async () => {
  1326. const { send, taskService } = setup();
  1327. await send("/enable");
  1328. await send("/history on");
  1329. historyMock.mockResolvedValueOnce({
  1330. messages: [
  1331. {
  1332. id: "om_background",
  1333. chatId: "oc_a",
  1334. threadId: "omt_empty",
  1335. senderId: "ou_user",
  1336. senderType: "user",
  1337. text: "What is two plus two",
  1338. createdAt: 1,
  1339. kind: "text",
  1340. },
  1341. ] as never[],
  1342. checkpoint: "om__ou_user",
  1343. hasGap: false,
  1344. });
  1345. await send("", "oc_a", "ou_user", "omt_empty");
  1346. const input = taskService.submitBotGroupInput.mock.calls[0]![0];
  1347. expect(input.content).toBe("");
  1348. expect(input.attachments).toEqual([
  1349. expect.objectContaining({
  1350. kind: "file",
  1351. sourceKind: "topic-history",
  1352. mimeType: "text/plain",
  1353. textContent: expect.stringContaining("What is two plus two"),
  1354. }),
  1355. ]);
  1356. expect(input.attachments[0].textContent).toContain("ou_user");
  1357. expect(input.content).not.toContain("What is two plus two");
  1358. expect(input.source.topicContext).toBeUndefined();
  1359. expect(JSON.stringify(input.source)).not.toContain("What is two plus two");
  1360. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1361. expect(taskService.submitBotGroupInput).toHaveBeenCalledWith(
  1362. expect.objectContaining({
  1363. source: expect.objectContaining({
  1364. topicHistory: expect.objectContaining({ checkpoint: "om__ou_user", messageCount: 1 }),
  1365. }),
  1366. }),
  1367. );
  1368. });
  1369. it("rejects a bare mention when opted-in history is unavailable", async () => {
  1370. const { send, taskService } = setup();
  1371. await send("/enable");
  1372. await send("/history on");
  1373. historyMock.mockRejectedValueOnce(new Error("history unavailable"));
  1374. expect((await send("", "oc_a", "ou_user", "omt_empty"))[0]?.text).toContain("重试");
  1375. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1376. });
  1377. it("keeps the last successful checkpoint when a history read is rejected", async () => {
  1378. const { send, taskService } = setup();
  1379. await send("/enable");
  1380. await send("/history on");
  1381. historyMock.mockResolvedValueOnce({
  1382. messages: [],
  1383. checkpoint: "om_first_ou_user",
  1384. hasGap: false,
  1385. });
  1386. await send("first", "oc_a", "ou_user", "omt_gap");
  1387. await send("/history on");
  1388. historyMock.mockRejectedValueOnce(new Error("history unavailable"));
  1389. await send("second", "oc_a", "ou_user", "omt_gap");
  1390. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1391. await send("third", "oc_a", "ou_user", "omt_gap");
  1392. expect(historyMock.mock.calls.at(-1)?.[1].checkpoint).toBe("om_first_ou_user");
  1393. });
  1394. it("preserves a history opt-in while an earlier input admission finishes", async () => {
  1395. const { send, repo, taskService } = setup();
  1396. await send("/enable");
  1397. const original = taskService.submitBotGroupInput!;
  1398. let release!: () => void;
  1399. let started!: () => void;
  1400. const ready = new Promise<void>((resolve) => {
  1401. started = resolve;
  1402. });
  1403. taskService.submitBotGroupInput = vi.fn(async (params) => {
  1404. started();
  1405. await new Promise<void>((resolve) => {
  1406. release = resolve;
  1407. });
  1408. return original(params);
  1409. });
  1410. const pending = send("work");
  1411. await ready;
  1412. await send("/history on", "oc_a", "ou_user", "omt_settings");
  1413. release();
  1414. await pending;
  1415. expect(
  1416. (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a"])]?.group?.historyEnabled,
  1417. ).toBe(true);
  1418. });
  1419. it("rejects admission if the group is disabled during topic history preparation", async () => {
  1420. const { send, taskService } = setup();
  1421. await send("/enable");
  1422. await send("/history on");
  1423. let release!: () => void;
  1424. let started!: () => void;
  1425. const ready = new Promise<void>((resolve) => {
  1426. started = resolve;
  1427. });
  1428. historyMock.mockImplementationOnce(async (_bot, request) => {
  1429. started();
  1430. await new Promise<void>((resolve) => {
  1431. release = resolve;
  1432. });
  1433. return { messages: [], checkpoint: request.messageId, hasGap: false };
  1434. });
  1435. const pending = send("pending history", "oc_a", "ou_user", "omt_race");
  1436. await ready;
  1437. await send("/disable");
  1438. release();
  1439. expect(await pending).toEqual([]);
  1440. await new Promise((resolve) => setTimeout(resolve, 0));
  1441. expect(taskService.createTask).not.toHaveBeenCalled();
  1442. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1443. });
  1444. it("scopes topic details to the bound task and workspace", async () => {
  1445. const { send, service, repo, taskService } = setup();
  1446. await send("/enable");
  1447. await send("topic request", "oc_a", "ou_user", "thread-a");
  1448. const state = (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a", "thread-a"])]!;
  1449. taskService.readBotTopicSummaries = vi.fn(async () => [
  1450. { checkpoint: "m1", text: "Decision: blue" },
  1451. ]);
  1452. const params = {
  1453. botId: "feishu-1",
  1454. chatId: "oc_a",
  1455. threadId: "thread-a",
  1456. taskId: state.activeTaskId!,
  1457. workspacePath: state.workspacePath!,
  1458. workspaceIdentity: state.workspaceIdentity,
  1459. };
  1460. expect(await service.getTopicDetails!(params)).toMatchObject({
  1461. summaries: [{ checkpoint: "m1", text: "Decision: blue" }],
  1462. messageCount: 0,
  1463. });
  1464. await expect(service.getTopicDetails!({ ...params, taskId: "unrelated" })).rejects.toThrow(
  1465. /scope/,
  1466. );
  1467. await expect(
  1468. service.getTopicDetails!({ ...params, workspaceIdentity: "ssh://other" }),
  1469. ).rejects.toThrow(/scope/);
  1470. });
  1471. it.each([false, true])(
  1472. "isolates reply topics and migrates old aliases once (legacy=%s)",
  1473. async (legacy) => {
  1474. const { send, repo, taskService } = setup(true);
  1475. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  1476. taskService.renameTask = vi.fn(async () => ({ taskId: "topic-task-1" }) as never);
  1477. await send("/enable");
  1478. const state = await repo.readState();
  1479. const key = JSON.stringify(["feishu-1", "oc_a"]);
  1480. state.bots[key]!.activeTaskId = "original-task";
  1481. state.bots[key]!.mode = "task";
  1482. state.bots[key]!.group!.taskIds = ["original-task"];
  1483. state.bots[key]!.group!.deliveries = {
  1484. result: {
  1485. id: "result",
  1486. taskId: "original-task",
  1487. text: "reply",
  1488. status: "sent",
  1489. updatedAt: 1,
  1490. providerMessageId: "root_omt_reply",
  1491. },
  1492. };
  1493. await repo.writeState(state);
  1494. if (legacy) {
  1495. state.bots[key]!.group!.topicAliases = {
  1496. omt_reply: { taskId: "original-task", rootMessageId: "root_omt_reply" },
  1497. };
  1498. state.bots[key]!.group!.taskWorkspaces = {
  1499. "original-task": { workspacePath: "/old-workspace", workspaceIdentity: "old-identity" },
  1500. };
  1501. await repo.writeState(state);
  1502. }
  1503. await send("first reply", "oc_a", "ou_user", "omt_reply");
  1504. await send("second reply", "oc_a", "ou_user", "omt_reply");
  1505. const after = await repo.readState();
  1506. const topic = after.bots[JSON.stringify(["feishu-1", "oc_a", "omt_reply"])];
  1507. expect(topic?.activeTaskId).toBe("topic-task-1");
  1508. expect(taskService.createTask).toHaveBeenCalledOnce();
  1509. if (legacy)
  1510. expect(taskService.getBotGroupTaskBlockReason).toHaveBeenCalledWith({
  1511. taskId: "original-task",
  1512. workspacePath: "/old-workspace",
  1513. workspaceIdentity: "old-identity",
  1514. });
  1515. expect(after.bots[key]?.group?.topicAliases?.omt_reply).toBeUndefined();
  1516. expect(taskService.renameTask).toHaveBeenCalledWith(
  1517. expect.objectContaining({ title: "飞书 · 测试群 · omt_reply" }),
  1518. );
  1519. expect(taskService.submitBotGroupInput.mock.calls.map(([input]) => input.taskId)).toEqual([
  1520. "topic-task-1",
  1521. "topic-task-1",
  1522. ]);
  1523. expect(after.bots[key]?.activeTaskId).toBe("original-task");
  1524. const [reply] = await send("/new", "oc_a", "ou_user", "omt_reply");
  1525. expect(reply.text).toMatch(/another topic|另开/);
  1526. },
  1527. );
  1528. it("reads history only on entry or explicit reconciliation and keeps the accepted checkpoint", async () => {
  1529. const { send, taskService } = setup();
  1530. await send("/enable");
  1531. await send("first", "oc_a", "ou_user", "omt_a");
  1532. expect(historyMock).toHaveBeenCalledOnce();
  1533. await send("/history on");
  1534. await send("second", "oc_a", "ou_user", "omt_a");
  1535. expect(historyMock).toHaveBeenLastCalledWith(
  1536. expect.anything(),
  1537. expect.objectContaining({
  1538. messageId: "om_second_ou_user",
  1539. checkpoint: "om_first_ou_user",
  1540. }),
  1541. );
  1542. await send("third", "oc_a", "ou_user", "omt_a");
  1543. expect(historyMock).toHaveBeenCalledTimes(2);
  1544. expect(
  1545. taskService.submitBotGroupInput.mock.calls.at(-1)?.[0].source.topicHistory,
  1546. ).toBeUndefined();
  1547. await send("/leave", "oc_a", "ou_user", "omt_a");
  1548. await send("resume", "oc_a", "ou_user", "omt_a");
  1549. expect(historyMock).toHaveBeenLastCalledWith(
  1550. expect.anything(),
  1551. expect.objectContaining({ checkpoint: "om_third_ou_user" }),
  1552. );
  1553. });
  1554. it("keeps history off until the owner explicitly enables it for the group", async () => {
  1555. const { send, repo } = setup();
  1556. await send("/enable");
  1557. const key = JSON.stringify(["feishu-1", "oc_a"]);
  1558. expect((await repo.readState()).bots[key]?.group?.historyEnabled).toBeFalsy();
  1559. await send("/history on", "oc_a", "member");
  1560. expect((await repo.readState()).bots[key]?.group?.historyEnabled).toBeFalsy();
  1561. await send("/history on", "oc_a", "ou_user", "omt_a");
  1562. expect((await repo.readState()).bots[key]?.group?.historyEnabled).toBe(true);
  1563. await send("/history off");
  1564. expect((await repo.readState()).bots[key]?.group?.historyEnabled).toBe(false);
  1565. });
  1566. it("carries topic identity through admission without a legacy queue card", async () => {
  1567. const { send, taskService, repo } = setup();
  1568. await send("/enable");
  1569. const [reply] = await send("topic request", "oc_a", "ou_user", "omt_a");
  1570. expect(taskService.submitBotGroupInput).toHaveBeenCalledWith(
  1571. expect.objectContaining({
  1572. source: expect.objectContaining({
  1573. threadId: "omt_a",
  1574. authorizationId: (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a"])]!
  1575. .group!.authorizationId,
  1576. }),
  1577. }),
  1578. );
  1579. expect(reply).toBeUndefined();
  1580. const [newReply] = await send("/new", "oc_a", "ou_user", "omt_a");
  1581. expect(newReply.text).toMatch(/another topic|另开/);
  1582. });
  1583. it("creates independent topic drafts from group defaults and keeps the default draft", async () => {
  1584. const { send, repo } = setup();
  1585. await send("/enable");
  1586. await send("/status", "oc_a", "ou_user", "omt_a");
  1587. await send("/status", "oc_a", "ou_user", "omt_b");
  1588. const { bots } = await repo.readState();
  1589. const a = bots[JSON.stringify(["feishu-1", "oc_a", "omt_a"])];
  1590. const b = bots[JSON.stringify(["feishu-1", "oc_a", "omt_b"])];
  1591. expect(a?.group?.threadId).toBe("omt_a");
  1592. expect(b?.group?.threadId).toBe("omt_b");
  1593. expect(a?.draftOptions?.mode).toBe("default");
  1594. expect(a?.group?.inputs).toBeUndefined();
  1595. expect(bots[JSON.stringify(["feishu-1", "oc_a"])].group?.threadId).toBeUndefined();
  1596. });
  1597. it("disables the entire group from a topic and invalidates sibling authorization", async () => {
  1598. const { send, repo } = setup();
  1599. await send("/enable");
  1600. await send("/status", "oc_a", "ou_user", "omt_a");
  1601. await send("/status", "oc_a", "ou_user", "omt_b");
  1602. await send("/disable", "oc_a", "ou_user", "omt_a");
  1603. const groups = Object.values((await repo.readState()).bots).filter((s) => s.group);
  1604. expect(groups).toHaveLength(3);
  1605. expect(groups.every((s) => s.group?.enabled === false)).toBe(true);
  1606. const [reply] = await send("/status", "oc_a", "member", "omt_b");
  1607. expect(reply?.text).toMatch(/not enabled|未启用/i);
  1608. });
  1609. it.each([undefined, "omt_fast"])(
  1610. "keeps completed progress and reaction before admission returns (%s)",
  1611. async (threadId) => {
  1612. const { send, taskService, repo } = setup();
  1613. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1614. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1615. emit = listener;
  1616. return { dispose: vi.fn() };
  1617. });
  1618. taskService.submitBotGroupInput = vi.fn(async (params) => {
  1619. await emit({
  1620. type: "task_run_started",
  1621. taskId: params.taskId,
  1622. inputId: params.commandId,
  1623. } as Parameters<typeof emit>[0]);
  1624. await emit({
  1625. type: "task_complete",
  1626. taskId: params.taskId,
  1627. inputId: params.commandId,
  1628. stopReason: "end_turn",
  1629. } as Parameters<typeof emit>[0]);
  1630. return {
  1631. commandId: params.commandId,
  1632. status: "accepted",
  1633. revisionAtDecision: 1,
  1634. result: { type: "inputAccepted", inputId: params.commandId, delivery: "queue" },
  1635. };
  1636. });
  1637. await send("/enable");
  1638. await send("fast completion", "oc_a", "ou_user", threadId);
  1639. const context = Object.values((await repo.readState()).bots).find(
  1640. (value) => value.group?.inputs,
  1641. )!;
  1642. const input = Object.values(context.group!.inputs!)[0]!;
  1643. expect(input.admission).toBe("accepted");
  1644. expect(input.progress?.status).toBe("done");
  1645. expect((reactionMock.mock.lastCall as unknown[] | undefined)?.[2]).toBe("done");
  1646. },
  1647. );
  1648. it.each(["task_complete", "task_error"] as const)(
  1649. "projects %s onto the original input reaction",
  1650. async (type) => {
  1651. const { send, taskService, repo } = setup();
  1652. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1653. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1654. emit = listener;
  1655. return { dispose: vi.fn() };
  1656. });
  1657. await send("/enable");
  1658. await send("reaction result", "oc_a", "ou_member");
  1659. const context = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  1660. const [inputId, input] = Object.entries(context.group!.inputs!)[0]!;
  1661. const saved = await repo.readState();
  1662. const savedContext = Object.values(saved.bots).find((value) => value.group)!;
  1663. savedContext.group!.inputs![inputId]!.progress = {
  1664. status: "waiting",
  1665. cardMessageId: "om_queue_card",
  1666. cardStatus: "waiting",
  1667. };
  1668. await repo.writeState(saved);
  1669. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1670. typeof emit
  1671. >[0]);
  1672. await emit({
  1673. type,
  1674. taskId: context.activeTaskId!,
  1675. inputId,
  1676. stopReason: "end_turn",
  1677. error: "test failure",
  1678. } as Parameters<typeof emit>[0]);
  1679. const last = reactionMock.mock.lastCall as unknown[] | undefined;
  1680. expect(last?.[1]).toBe(input.source.messageId);
  1681. expect(last?.[2]).toBe(type === "task_error" ? "failed" : "done");
  1682. const cardCalls = cardUpdateMock.mock.calls as unknown as Array<
  1683. [unknown, { providerMessageId: string }, { text: string; selection?: unknown }]
  1684. >;
  1685. expect(cardCalls.map((call) => call[1].providerMessageId)).toEqual([
  1686. "om_queue_card",
  1687. "om_queue_card",
  1688. ]);
  1689. expect(cardCalls.map((call) => call[2].text)).toEqual([
  1690. "正在执行",
  1691. type === "task_error" ? "执行失败" : "已完成",
  1692. ]);
  1693. expect(cardCalls.every((call) => call[2].selection === undefined)).toBe(true);
  1694. },
  1695. );
  1696. it.each(["task_complete", "turn_steer_status"])(
  1697. "does not send old topic queue or stop notices for %s",
  1698. async (type) => {
  1699. const { send, taskService, repo } = setup();
  1700. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1701. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1702. emit = listener;
  1703. return { dispose: vi.fn() };
  1704. });
  1705. await send("/enable");
  1706. await send("topic input", "oc_a", "ou_user", "omt_notices");
  1707. const key = JSON.stringify(["feishu-1", "oc_a", "omt_notices"]);
  1708. const context = (await repo.readState()).bots[key]!;
  1709. const inputId = Object.keys(context.group!.inputs!)[0]!;
  1710. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1711. typeof emit
  1712. >[0]);
  1713. await emit({
  1714. type,
  1715. taskId: context.activeTaskId!,
  1716. inputId,
  1717. stopReason: "cancelled",
  1718. status: "discarded",
  1719. reason: "session_resumed",
  1720. pendingInputIds: [inputId],
  1721. } as Parameters<typeof emit>[0]);
  1722. expect(Object.values((await repo.readState()).bots[key]!.group!.deliveries ?? {})).toEqual(
  1723. [],
  1724. );
  1725. expect((reactionMock.mock.calls.at(-1) as unknown[] | undefined)?.[2]).toBe("cancelled");
  1726. expect((await repo.readState()).bots[key]!.group!.inputs![inputId]!.progress?.status).toBe(
  1727. type === "task_complete" ? "stopped" : "discarded",
  1728. );
  1729. },
  1730. );
  1731. it.each(["Alice", "ou_member"])(
  1732. "keeps stopped group runs silent while updating reactions (%s)",
  1733. async (senderName) => {
  1734. const { send, taskService, repo } = setup();
  1735. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1736. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1737. emit = listener;
  1738. return { dispose: vi.fn() };
  1739. });
  1740. await send("/enable");
  1741. await send("hello", "oc_a", "ou_member");
  1742. const state = await repo.readState();
  1743. const context = Object.values(state.bots).find((value) => value.group)!;
  1744. const [inputId, input] = Object.entries(context.group!.inputs!)[0]!;
  1745. input.source.senderName = senderName;
  1746. await repo.writeState(state);
  1747. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1748. typeof emit
  1749. >[0]);
  1750. await emit({
  1751. type: "task_complete",
  1752. taskId: context.activeTaskId!,
  1753. inputId,
  1754. stopReason: "cancelled",
  1755. } as Parameters<typeof emit>[0]);
  1756. const updated = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  1757. expect(Object.values(updated.group!.deliveries ?? {})).toEqual([]);
  1758. expect(reactionMock.mock.calls.map((call) => (call as unknown[])[2])).toEqual([
  1759. "waiting",
  1760. "working",
  1761. "cancelled",
  1762. ]);
  1763. },
  1764. );
  1765. it("keeps each run's reply target when another member speaks and clears it for desktop runs", async () => {
  1766. const { send, taskService, repo } = setup();
  1767. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1768. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1769. emit = listener;
  1770. return { dispose: vi.fn() };
  1771. });
  1772. await send("/enable");
  1773. await send("first", "oc_a", "ou_alice");
  1774. await send("second", "oc_a", "ou_bob");
  1775. const context = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  1776. const inputs = Object.entries(context.group!.inputs!);
  1777. expect(inputs).toHaveLength(2);
  1778. for (const [inputId] of [...inputs, ["desktop-run", undefined]]) {
  1779. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1780. typeof emit
  1781. >[0]);
  1782. await emit({
  1783. type: "task_complete",
  1784. taskId: context.activeTaskId!,
  1785. inputId,
  1786. stopReason: "error",
  1787. error: "example failure",
  1788. } as Parameters<typeof emit>[0]);
  1789. }
  1790. const updated = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  1791. const results = Object.values(updated.group!.deliveries!);
  1792. expect(results).toHaveLength(3);
  1793. for (const [index, [, input]] of inputs.entries()) {
  1794. expect(results[index]).toMatchObject({
  1795. replyToMessageId: input.source.messageId,
  1796. mentionedUserIds: [input.source.senderId],
  1797. });
  1798. }
  1799. expect(results[2]?.replyToMessageId).toBeUndefined();
  1800. expect(results[2]?.mentionedUserIds).toBeUndefined();
  1801. });
  1802. it("quotes the batch boundary and mentions deduplicated participants only on the first saved part", async () => {
  1803. const { send, taskService, repo } = setup();
  1804. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1805. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1806. emit = listener;
  1807. return { dispose: vi.fn() };
  1808. });
  1809. await send("/enable");
  1810. await send("batch", "oc_a", "ou_bob", "omt_batch");
  1811. const state = await repo.readState();
  1812. const context = Object.values(state.bots).find(
  1813. (value) => value.group?.threadId === "omt_batch",
  1814. )!;
  1815. const [inputId, input] = Object.entries(context.group!.inputs!)[0]!;
  1816. input.source.messages = [
  1817. {
  1818. messageId: "om_first",
  1819. senderId: "ou_alice",
  1820. senderName: "Alice",
  1821. mentionedBot: true,
  1822. text: "first",
  1823. attachmentIndexes: [],
  1824. },
  1825. {
  1826. messageId: "om_next",
  1827. senderId: "ou_alice",
  1828. senderName: "Alice",
  1829. text: "next",
  1830. attachmentIndexes: [],
  1831. },
  1832. {
  1833. messageId: input.source.messageId,
  1834. senderId: "ou_bob",
  1835. senderName: "Bob",
  1836. text: "last",
  1837. attachmentIndexes: [],
  1838. },
  1839. ];
  1840. await repo.writeState(state);
  1841. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1842. typeof emit
  1843. >[0]);
  1844. await emit({
  1845. type: "task_error",
  1846. taskId: context.activeTaskId!,
  1847. inputId,
  1848. error: "错误详情".repeat(1100),
  1849. } as Parameters<typeof emit>[0]);
  1850. const updated = Object.values((await repo.readState()).bots).find(
  1851. (value) => value.group?.threadId === "omt_batch",
  1852. )!;
  1853. const results = Object.values(updated.group!.deliveries!);
  1854. expect(results.length).toBeGreaterThan(1);
  1855. for (const [index, result] of results.entries()) {
  1856. expect(result.replyToMessageId).toBe(input.source.messageId);
  1857. expect(result.threadId).toBe("omt_batch");
  1858. expect(result.mentionedUserIds).toEqual(index === 0 ? ["ou_alice"] : undefined);
  1859. }
  1860. });
  1861. it("reads names only for an enabled authorized group", async () => {
  1862. const { send, service } = setup();
  1863. const params = { botId: "feishu-1", chatId: "oc_a" };
  1864. await expect(service.getGroupMemberNames!(params)).rejects.toThrow();
  1865. await send("/enable");
  1866. expect(await service.getGroupMemberNames!(params)).toEqual({ ou_user: "Alice" });
  1867. await expect(service.getGroupMemberNames!({ ...params, chatId: "oc_other" })).rejects.toThrow();
  1868. await send("/disable");
  1869. await expect(service.getGroupMemberNames!(params)).rejects.toThrow();
  1870. });
  1871. it("rejects a directory response after the group is disabled during lookup", async () => {
  1872. const { send, service } = setup();
  1873. await send("/enable");
  1874. let finish!: (names: Record<string, string>) => void;
  1875. directoryMock.mockImplementationOnce(
  1876. () =>
  1877. new Promise((resolve) => {
  1878. finish = resolve;
  1879. }),
  1880. );
  1881. const reading = service.getGroupMemberNames!({ botId: "feishu-1", chatId: "oc_a" });
  1882. const rejection = expect(reading).rejects.toThrow("unavailable");
  1883. await vi.waitFor(() => expect(directoryMock).toHaveBeenCalledTimes(1));
  1884. await send("/disable");
  1885. finish({ ou_user: "Alice" });
  1886. await rejection;
  1887. });
  1888. it("reconciles only saved unknown results in the currently authorized group", async () => {
  1889. const { send, service, repo } = setup();
  1890. await send("/enable");
  1891. await send("work", "oc_a", "member");
  1892. const state = await repo.readState();
  1893. const context = Object.values(state.bots).find((value) => value.group)!;
  1894. context.group!.deliveries = {
  1895. unknown: {
  1896. id: "unknown",
  1897. taskId: context.activeTaskId!,
  1898. text: "saved",
  1899. status: "unknown",
  1900. updatedAt: 1,
  1901. },
  1902. };
  1903. await repo.writeState(state);
  1904. expect(
  1905. await service.reconcileGroupResult({
  1906. botId: "feishu-1",
  1907. chatId: "oc_a",
  1908. deliveryId: "unknown",
  1909. received: true,
  1910. }),
  1911. ).toMatchObject({ status: "sent", text: "saved" });
  1912. await expect(
  1913. service.reconcileGroupResult({
  1914. botId: "feishu-1",
  1915. chatId: "oc_a",
  1916. deliveryId: "unknown",
  1917. received: false,
  1918. }),
  1919. ).rejects.toThrow();
  1920. context.group!.deliveries!.unknown!.status = "unknown";
  1921. await send("/disable");
  1922. await expect(
  1923. service.reconcileGroupResult({
  1924. botId: "feishu-1",
  1925. chatId: "oc_a",
  1926. deliveryId: "unknown",
  1927. received: false,
  1928. }),
  1929. ).rejects.toThrow();
  1930. });
  1931. it("refuses to resend a saved result from an earlier authorization generation", async () => {
  1932. const { send, service, repo } = setup();
  1933. await send("/enable");
  1934. await send("work", "oc_a", "member");
  1935. const state = await repo.readState();
  1936. const context = Object.values(state.bots).find((value) => value.group)!;
  1937. context.group!.deliveries = {
  1938. old: {
  1939. id: "old",
  1940. taskId: context.activeTaskId!,
  1941. text: "old",
  1942. status: "failed",
  1943. authorizationId: "earlier-generation",
  1944. updatedAt: 1,
  1945. },
  1946. };
  1947. await repo.writeState(state);
  1948. expect(
  1949. await service.resendGroupResult({ botId: "feishu-1", chatId: "oc_a", deliveryId: "old" }),
  1950. ).toMatchObject({ status: "invalidated" });
  1951. });
  1952. it("requires owner activation, keeps private state and two groups independent", async () => {
  1953. const { service, send, repo } = setup();
  1954. expect((await send("/enable", "oc_a", "member"))[0]?.text).toContain("绑定");
  1955. expect((await service.getBotStates()).filter((s) => s.group)).toHaveLength(0);
  1956. await service.handleInboundMessage({
  1957. botId: "feishu-1",
  1958. actor: {
  1959. provider: "feishu",
  1960. botId: "feishu-1",
  1961. providerUserId: "ou_user",
  1962. chatType: "private",
  1963. },
  1964. text: "/status",
  1965. });
  1966. await send("/enable");
  1967. await send("/enable", "oc_b");
  1968. const groups = (await service.getBotStates()).filter((s) => s.group);
  1969. expect(groups).toHaveLength(2);
  1970. expect(groups.map((s) => s.group?.chatId).sort()).toEqual(["oc_a", "oc_b"]);
  1971. expect(groups.every((s) => s.draftOptions?.mode === "default")).toBe(true);
  1972. const before = structuredClone(await repo.readState());
  1973. await send("/enable");
  1974. expect(await repo.readState()).toEqual(before);
  1975. const memberStatus = await send("/status", "oc_a", "member");
  1976. expect(memberStatus[0]?.providerUserId).toBe("oc_a");
  1977. expect(memberStatus.map((r) => r.text).join("\n")).not.toContain("/tmp/workspace");
  1978. expect((await send("/new", "oc_a", "member"))[0]?.text).toContain("绑定");
  1979. });
  1980. it("disables only the selected group and re-enables without resetting it", async () => {
  1981. const { service, send } = setup();
  1982. await send("/enable");
  1983. await send("/enable", "oc_b");
  1984. await send("/disable");
  1985. let states = await service.getBotStates();
  1986. expect(states.find((s) => s.group?.chatId === "oc_a")?.group?.enabled).toBe(false);
  1987. expect(states.find((s) => s.group?.chatId === "oc_b")?.group?.enabled).toBe(true);
  1988. expect((await send("hello", "oc_a", "member"))[0]?.text).toContain("启用");
  1989. await send("/enable");
  1990. states = await service.getBotStates();
  1991. expect(states.find((s) => s.group?.chatId === "oc_a")?.group?.enabled).toBe(true);
  1992. });
  1993. it("does not readmit an accepted or uncertain provider message after in-memory dedupe is gone", async () => {
  1994. const { send, taskService } = setup();
  1995. await send("/enable");
  1996. await send("accepted-once", "oc_a", "member");
  1997. await send("accepted-once", "oc_a", "member");
  1998. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1999. vi.mocked(taskService.submitBotGroupInput).mockRejectedValueOnce(
  2000. new Error("lost acknowledgement"),
  2001. );
  2002. await expect(send("uncertain-once", "oc_a", "member")).rejects.toThrow("lost acknowledgement");
  2003. const retry = await send("uncertain-once", "oc_a", "member");
  2004. expect(retry[0]?.text).toContain("核对");
  2005. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  2006. });
  2007. it("admits member inputs through the canonical queue without legacy send or yolo", async () => {
  2008. const { send, taskService } = setup();
  2009. await send("/enable");
  2010. expect((await send("first", "oc_a", "member"))[0]?.text).toContain("等待执行");
  2011. expect((await send("second", "oc_a", "other"))[0]?.text).toContain("等待执行");
  2012. expect(taskService.createTask).toHaveBeenCalledTimes(1);
  2013. expect(taskService.createTask).toHaveBeenCalledWith(
  2014. expect.objectContaining({ permissionScope: "session" }),
  2015. );
  2016. expect(taskService.sendPrompt).not.toHaveBeenCalled();
  2017. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  2018. expect(taskService.submitBotGroupInput).toHaveBeenLastCalledWith(
  2019. expect.objectContaining({
  2020. source: expect.objectContaining({
  2021. chatId: "oc_a",
  2022. senderId: "other",
  2023. messageId: "om_second_other",
  2024. }),
  2025. }),
  2026. );
  2027. expect(taskService.setMode).toHaveBeenCalledWith(expect.objectContaining({ mode: "default" }));
  2028. });
  2029. it("does not resolve another group's task through the direct snapshot fallback", async () => {
  2030. const { send, taskService } = setup();
  2031. await send("/enable");
  2032. await send("/task foreign-task");
  2033. expect(taskService.getTaskSnapshot).not.toHaveBeenCalledWith(
  2034. expect.objectContaining({ taskId: "foreign-task" }),
  2035. );
  2036. });
  2037. it("does not expose the local absolute workspace path in group status", async () => {
  2038. const { send, service } = setup();
  2039. await send("/enable");
  2040. const path = (await service.getBotStates()).find((state) => state.group)!.workspacePath;
  2041. expect(path.startsWith("/")).toBe(true);
  2042. expect((await send("/status", "oc_a", "member"))[0]!.text).not.toContain(path);
  2043. });
  2044. it("inherits structured task selection into a topic instead of parsing its display model", async () => {
  2045. const { send, taskService, repo } = setup(true);
  2046. await send("/enable");
  2047. await send("parent");
  2048. const parent = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  2049. taskService.listTasks = vi.fn(async () => [
  2050. {
  2051. taskId: parent.activeTaskId!,
  2052. provider: "glm",
  2053. model: "glm/default$max",
  2054. title: "Parent",
  2055. workspacePath: "/tmp/workspace",
  2056. },
  2057. ]) as typeof taskService.listTasks;
  2058. taskService.getTaskModelSelection = vi.fn(async () => ({
  2059. providerId: "glm",
  2060. modelId: "default",
  2061. options: { reasoningLevel: "max" },
  2062. }));
  2063. await send("topic", "oc_a", "ou_user", "omt_selection");
  2064. const topic = Object.values((await repo.readState()).bots).find(
  2065. (value) => value.group?.threadId === "omt_selection",
  2066. )!;
  2067. expect(taskService.getTaskModelSelection).toHaveBeenCalledWith({ taskId: parent.activeTaskId });
  2068. const creation = vi.mocked(taskService.createTask).mock.calls.at(-1)?.[0];
  2069. expect(creation?.modelSelection ?? topic.draftOptions?.modelSelection).toEqual({
  2070. providerId: "glm",
  2071. modelId: "default",
  2072. options: { reasoningLevel: "max" },
  2073. });
  2074. });
  2075. it("inherits the group's explicit draft selection before any parent task exists", async () => {
  2076. const { send, repo } = setup();
  2077. await send("/enable");
  2078. const state = await repo.readState();
  2079. const parent = Object.values(state.bots).find((value) => value.group)!;
  2080. parent.draftOptions = {
  2081. provider: "glm",
  2082. modelSelection: {
  2083. providerId: "glm",
  2084. modelId: "default",
  2085. options: { reasoningLevel: "high" },
  2086. },
  2087. };
  2088. await repo.writeState(state);
  2089. await send("/status", "oc_a", "ou_user", "omt_draft");
  2090. const topic = Object.values((await repo.readState()).bots).find(
  2091. (value) => value.group?.threadId === "omt_draft",
  2092. )!;
  2093. expect(topic.draftOptions?.modelSelection).toEqual(parent.draftOptions.modelSelection);
  2094. });
  2095. it("inherits the current model selection when enabling a group", async () => {
  2096. const { send, repo, service } = setup();
  2097. const config = await repo.readConfig();
  2098. const modelSelection = {
  2099. providerId: "glm",
  2100. modelId: "default",
  2101. options: { reasoningLevel: "high" },
  2102. };
  2103. config.bots[0]!.currentOptions = { modelSelection, mode: "yolo" };
  2104. await repo.writeConfig(config);
  2105. await send("/enable");
  2106. const group = (await service.getBotStates()).find((state) => state.group)?.group;
  2107. expect(group?.currentOptions).toEqual({ modelSelection, mode: "default" });
  2108. });
  2109. it("does not inherit private sandbox and approval overrides", async () => {
  2110. const { send, repo, service } = setup();
  2111. const config = await repo.readConfig();
  2112. config.bots[0]!.currentOptions = {
  2113. mode: "yolo",
  2114. sandboxMode: "danger-full-access",
  2115. approvalPolicy: "never",
  2116. };
  2117. await repo.writeConfig(config);
  2118. await send("/enable");
  2119. const group = (await service.getBotStates()).find((s) => s.group)?.group;
  2120. expect(group?.currentOptions).toEqual({ mode: "default" });
  2121. });
  2122. it("refuses new drafts while CLI still owns queued input, even without a bot running marker", async () => {
  2123. const { send, taskService, service } = setup();
  2124. taskService.getBotGroupTaskBlockReason = vi.fn(async () => "queued" as const);
  2125. await send("/enable");
  2126. await send("work", "oc_a", "member");
  2127. const taskId = (await service.getBotStates()).find((s) => s.group)?.activeTaskId;
  2128. const reply = await send("/new");
  2129. expect(reply[0]?.text).toContain("排队");
  2130. expect((await service.getBotStates()).find((s) => s.group)?.activeTaskId).toBe(taskId);
  2131. });
  2132. it.each([
  2133. ["running", "运行"],
  2134. ["queued", "排队"],
  2135. ["interaction", "回答或审批"],
  2136. ] as const)("reports the CLI blocking reason %s", async (reason, expected) => {
  2137. const { send, taskService, service } = setup();
  2138. taskService.getBotGroupTaskBlockReason = vi.fn(async () => reason);
  2139. await send("/enable");
  2140. await send("work", "oc_a", "member");
  2141. const taskId = (await service.getBotStates()).find((value) => value.group)?.activeTaskId;
  2142. expect((await send("/new"))[0]?.text).toContain(expected);
  2143. expect((await service.getBotStates()).find((value) => value.group)?.activeTaskId).toBe(taskId);
  2144. });
  2145. it("opens a new draft after stop despite stale Bot permission options", async () => {
  2146. const { send, repo, service, taskService } = setup();
  2147. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  2148. await send("/enable");
  2149. await send("work", "oc_a", "member");
  2150. const state = await repo.readState();
  2151. const context = Object.values(state.bots).find((value) => value.group)!;
  2152. context.pendingPermissionOptions = [
  2153. {
  2154. requestId: "stopped-permission",
  2155. optionId: "allow_once",
  2156. command: "approve",
  2157. label: "Allow",
  2158. response: { decision: "allow", reason: "Approved once" },
  2159. },
  2160. ];
  2161. await repo.writeState(state);
  2162. vi.mocked(taskService.getBotGroupTaskBlockReason).mockClear();
  2163. await send("/new");
  2164. expect(taskService.getBotGroupTaskBlockReason).toHaveBeenCalledOnce();
  2165. const updated = (await service.getBotStates()).find((value) => value.group)!;
  2166. expect(updated.activeTaskId).toBeNull();
  2167. expect(updated.pendingPermissionOptions ?? []).toHaveLength(0);
  2168. });
  2169. it("allows only the queued input author or owner to cancel through CLI", async () => {
  2170. const { send, taskService } = setup();
  2171. taskService.cancelBotGroupInput = vi.fn(async (params) => ({
  2172. commandId: params.commandId,
  2173. status: "accepted",
  2174. revisionAtDecision: 2,
  2175. }));
  2176. await send("/enable");
  2177. const queued = await send("work", "oc_a", "member");
  2178. const cancel = queued[0]?.selection?.options[0]?.id;
  2179. expect(cancel).toMatch(/^\/queue-cancel /);
  2180. await send(cancel!, "oc_a", "other");
  2181. expect(taskService.cancelBotGroupInput).not.toHaveBeenCalled();
  2182. await send(cancel!, "oc_a", "member");
  2183. expect(taskService.cancelBotGroupInput).toHaveBeenCalledOnce();
  2184. });
  2185. it.each(["member", "ou_user"])(
  2186. "rejects legacy topic queue cancellation even from %s",
  2187. async (actorId) => {
  2188. const { send, service, repo, taskService } = setup(true);
  2189. taskService.cancelBotGroupInput = vi.fn();
  2190. await send("/enable");
  2191. await send("request A", "oc_a", "member", "omt_a");
  2192. const before = await repo.readState();
  2193. const context = before.bots[JSON.stringify(["feishu-1", "oc_a", "omt_a"])]!;
  2194. const commandId = Object.keys(context.group!.inputs!)[0]!;
  2195. const response = await service.handleInboundMessage({
  2196. botId: "feishu-1",
  2197. text: `/queue-cancel ${commandId}`,
  2198. groupCard: {
  2199. chatId: "oc_a",
  2200. threadId: "omt_a",
  2201. taskId: context.activeTaskId,
  2202. authorizationId: context.group!.authorizationId,
  2203. },
  2204. actor: {
  2205. botId: "feishu-1",
  2206. provider: "feishu",
  2207. chatType: "group",
  2208. chatId: "oc_a",
  2209. threadId: "omt_a",
  2210. rootMessageId: "root_omt_a",
  2211. providerUserId: actorId,
  2212. },
  2213. });
  2214. expect(taskService.cancelBotGroupInput).not.toHaveBeenCalled();
  2215. expect(response[0]?.callbackToastOnly).toBe(true);
  2216. expect(
  2217. (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a", "omt_a"])]!.group!.inputs,
  2218. ).toEqual(context.group!.inputs);
  2219. },
  2220. );
  2221. it("admits queue cancellation while another input is waiting for CLI acknowledgement", async () => {
  2222. const { send, taskService } = setup();
  2223. taskService.cancelBotGroupInput = vi.fn(async (params) => ({
  2224. commandId: params.commandId,
  2225. status: "accepted",
  2226. revisionAtDecision: 2,
  2227. }));
  2228. await send("/enable");
  2229. const first = await send("first", "oc_a", "member");
  2230. let release!: () => void;
  2231. taskService.submitBotGroupInput = vi.fn(async (params) => {
  2232. await new Promise<void>((resolve) => {
  2233. release = resolve;
  2234. });
  2235. return {
  2236. commandId: params.commandId,
  2237. status: "accepted",
  2238. revisionAtDecision: 2,
  2239. result: { type: "inputAccepted", inputId: params.commandId, delivery: "queue" },
  2240. };
  2241. });
  2242. const pending = send("second", "oc_a", "member");
  2243. await vi.waitFor(() => expect(taskService.submitBotGroupInput).toHaveBeenCalled());
  2244. try {
  2245. await send(first[0]!.selection!.options[0]!.id, "oc_a", "member");
  2246. expect(taskService.cancelBotGroupInput).toHaveBeenCalledOnce();
  2247. } finally {
  2248. release();
  2249. await pending;
  2250. }
  2251. }, 2500);
  2252. it("keeps a group's task selection when the private conversation opens a draft", async () => {
  2253. const { send, service, taskService } = setup();
  2254. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  2255. await send("/enable");
  2256. await send("work", "oc_a", "member");
  2257. const created = await taskService.createTask.mock.results[0]!.value;
  2258. taskService.listTasks = vi.fn(async () => [created]);
  2259. await send("/new");
  2260. const menu = await send("/task");
  2261. expect(menu[0]?.selection?.options.length).toBeGreaterThan(0);
  2262. await service.handleInboundMessage({
  2263. botId: "feishu-1",
  2264. actor: {
  2265. botId: "feishu-1",
  2266. provider: "feishu",
  2267. providerUserId: "ou_user",
  2268. chatType: "private",
  2269. },
  2270. text: "/new",
  2271. });
  2272. taskService.listTasks = vi.fn(async () => []);
  2273. await send("/task 1");
  2274. expect((await service.getBotStates()).find((value) => value.group)?.activeTaskId).toBe(
  2275. "task-1",
  2276. );
  2277. });
  2278. it("retains historical workspace identity when a group moves to another workspace", async () => {
  2279. const { send, service, taskService, repo } = setup();
  2280. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  2281. await send("/enable");
  2282. await send("history", "oc_a", "member");
  2283. let state = await repo.readState();
  2284. const context = Object.values(state.bots).find((value) => value.group)!;
  2285. const originalPath = context.workspacePath;
  2286. expect(context.group?.taskWorkspaces?.[context.activeTaskId!]).toMatchObject({
  2287. workspacePath: originalPath,
  2288. });
  2289. const originalTaskId = context.activeTaskId!;
  2290. context.workspacePath = "/another-group-workspace";
  2291. context.workspaceIdentity = undefined;
  2292. context.workspaceId = context.workspacePath;
  2293. context.activeTaskId = null;
  2294. context.mode = "draft";
  2295. await repo.writeState(state);
  2296. taskService.listTasks = vi.fn(async (params) =>
  2297. params.workspacePath === originalPath
  2298. ? [
  2299. {
  2300. taskId: originalTaskId,
  2301. title: "Historical group task",
  2302. workspacePath: originalPath,
  2303. provider: "glm",
  2304. },
  2305. ]
  2306. : [],
  2307. );
  2308. const menu = await send("/task");
  2309. expect(menu[0]?.selection?.options.map((option) => option.id)).toContain(originalTaskId);
  2310. expect((await service.getBotStates()).find((value) => value.group)?.activeTaskId).toBeNull();
  2311. });
  2312. it("invalidates group cards across disable and re-enable", async () => {
  2313. const { send, service } = setup();
  2314. await send("/enable");
  2315. const previous = (await service.getBotStates()).find((s) => s.group)!;
  2316. await send("/disable");
  2317. await send("/enable");
  2318. const reply = await service.handleInboundMessage({
  2319. botId: "feishu-1",
  2320. text: "/status",
  2321. actor: {
  2322. botId: "feishu-1",
  2323. provider: "feishu",
  2324. chatType: "group",
  2325. chatId: "oc_a",
  2326. providerUserId: "ou_user",
  2327. },
  2328. groupCard: {
  2329. chatId: "oc_a",
  2330. taskId: previous.activeTaskId,
  2331. authorizationId: previous.group!.authorizationId!,
  2332. },
  2333. });
  2334. expect(reply[0]?.callbackToastOnly).toBe(true);
  2335. expect(reply[0]?.text).toContain("过期");
  2336. });
  2337. it("requires fresh group authorization after owner replacement, including changing back", async () => {
  2338. const { send, service } = setup();
  2339. await send("/enable");
  2340. const config = structuredClone(await service.getConfig());
  2341. config.bots[0]!.providerUserId = "new-owner";
  2342. await service.saveConfig(config);
  2343. config.bots[0]!.providerUserId = "ou_user";
  2344. await service.saveConfig(config);
  2345. expect((await service.getBotStates()).find((s) => s.group)?.group?.enabled).toBe(false);
  2346. expect((await send("hello", "oc_a", "member"))[0]?.text).toContain("启用");
  2347. });
  2348. it("lets a replacement owner explicitly authorize a fresh group context", async () => {
  2349. const { send, service } = setup();
  2350. await send("/enable");
  2351. const previous = (await service.getBotStates()).find((s) => s.group)!;
  2352. const config = structuredClone(await service.getConfig());
  2353. config.bots[0]!.providerUserId = "new-owner";
  2354. await service.saveConfig(config);
  2355. await send("/enable", "oc_a", "new-owner");
  2356. const current = (await service.getBotStates()).find((s) => s.group)!;
  2357. expect(current.group?.ownerId).toBe("new-owner");
  2358. expect(current.group?.enabled).toBe(true);
  2359. expect(current.group?.authorizationId).not.toBe(previous.group?.authorizationId);
  2360. expect(current.activeTaskId).toBeNull();
  2361. expect(current.group?.taskIds).toEqual([]);
  2362. });
  2363. it("cancels pending topic material when the bot is removed from the group", async () => {
  2364. const { send, service, taskService } = setup();
  2365. await send("/enable");
  2366. let release!: () => void;
  2367. historyMock.mockImplementationOnce(async (_bot, request) => {
  2368. await new Promise<void>((resolve) => {
  2369. release = resolve;
  2370. });
  2371. return { messages: [], checkpoint: request.messageId, hasGap: false };
  2372. });
  2373. const pending = send("removed material", "oc_a", "ou_user", "omt_removed");
  2374. await vi.waitFor(() => expect(release).toBeTypeOf("function"));
  2375. const response = await service.handleProviderCallbackResponse("feishu", {
  2376. botId: "feishu-1",
  2377. zcodeBotRemoved: true,
  2378. event: { chat_id: "oc_a" },
  2379. });
  2380. expect(response.ok).toBe(true);
  2381. release();
  2382. expect(await pending).toEqual([]);
  2383. await new Promise((resolve) => setTimeout(resolve, 0));
  2384. expect(taskService.createTask).not.toHaveBeenCalled();
  2385. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  2386. });
  2387. it("rejects an unverified bot removal event before revoking a group", async () => {
  2388. const { send, service, repo } = setup();
  2389. await send("/enable");
  2390. const config = await repo.readConfig();
  2391. config.bots[0]!.webhookSecretRef = "verification-secret";
  2392. await repo.writeConfig(config);
  2393. // 测试凭据服务对未登记的引用返回 null;下面使用实际登记凭据的独立服务。
  2394. const secured = f.createBotsService({
  2395. zcodeTaskService: f.createLegacyTaskService(),
  2396. repo: repo as never,
  2397. credentialService: f.createCredentialService({ "verification-secret": "expected-token" }),
  2398. runStartupBackgroundTasks: false,
  2399. });
  2400. services.push(secured);
  2401. const response = await secured.handleProviderCallbackResponse("feishu", {
  2402. botId: "feishu-1",
  2403. zcodeBotRemoved: true,
  2404. token: "incorrect-token",
  2405. event: { chat_id: "oc_a" },
  2406. });
  2407. expect(response.ok).toBe(false);
  2408. expect((await service.getBotStates()).find((s) => s.group)?.group?.enabled).toBe(true);
  2409. });
  2410. it("stops group synchronization on disable and restores only future events on enable", async () => {
  2411. const { send, taskService } = setup();
  2412. const dispose = vi.fn();
  2413. const ready = vi.fn(async () => null);
  2414. taskService.getBotGroupTaskBlockReason = ready;
  2415. const subscribe = vi.fn(() => () => ({ dispose }));
  2416. taskService.onDynamicTaskEvent = subscribe as never;
  2417. await send("/enable");
  2418. await send("E2E_GROUP_RESTORE", "oc_a", "member");
  2419. expect(subscribe).toHaveBeenCalledOnce();
  2420. await send("/disable");
  2421. expect(dispose).toHaveBeenCalledOnce();
  2422. await send("/enable");
  2423. expect(subscribe).toHaveBeenCalledTimes(2);
  2424. expect(ready).toHaveBeenCalled();
  2425. expect(ready.mock.invocationCallOrder.at(-1)).toBeLessThan(
  2426. subscribe.mock.invocationCallOrder.at(-1)!,
  2427. );
  2428. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  2429. expect(taskService.resumeTask).not.toHaveBeenCalled();
  2430. });
  2431. it("does not replay a persisted old message into the next group draft", async () => {
  2432. const { send, taskService } = setup();
  2433. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  2434. await send("/enable");
  2435. await send("persisted-message", "oc_a", "member");
  2436. await send("/new");
  2437. await send("persisted-message", "oc_a", "member");
  2438. expect(taskService.createTask).toHaveBeenCalledOnce();
  2439. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  2440. });
  2441. it("persists the default group title after first admission", async () => {
  2442. const { send, taskService } = setup();
  2443. taskService.renameTask = vi.fn(async () => ({ taskId: "task-1" }) as never);
  2444. await send("/enable");
  2445. await send("first-title", "oc_a", "member");
  2446. expect(taskService.renameTask).toHaveBeenCalledWith(
  2447. expect.objectContaining({ taskId: "task-1", title: "飞书 · 测试群" }),
  2448. );
  2449. });
  2450. it("rejects an automation target that only has a legacy default-task alias", async () => {
  2451. const { send, service, taskService, repo } = setup();
  2452. await send("/enable");
  2453. const state = await repo.readState();
  2454. state.bots[JSON.stringify(["feishu-1", "oc_a"])].group!.topicAliases = {
  2455. omt_reply: { taskId: "original-task", rootMessageId: "om_reply" },
  2456. };
  2457. await repo.writeState(state);
  2458. taskService.onDynamicTaskEvent = vi.fn(() => () => ({ dispose() {} })) as never;
  2459. await service.watchAutomationRun({
  2460. workspacePath: "/tmp/workspace",
  2461. taskId: "scheduled-task",
  2462. target: {
  2463. provider: "feishu",
  2464. botId: "feishu-1",
  2465. providerUserId: "oc_a",
  2466. chatType: "group",
  2467. threadId: "omt_reply",
  2468. rootMessageId: "om_reply",
  2469. },
  2470. });
  2471. expect(taskService.onDynamicTaskEvent).not.toHaveBeenCalled();
  2472. });
  2473. it("does not attach a topic automation after its group is disabled", async () => {
  2474. const { send, service, taskService } = setup();
  2475. taskService.onDynamicTaskEvent = vi.fn(() => () => ({ dispose() {} })) as never;
  2476. await send("/enable");
  2477. await send("/status", "oc_a", "ou_user", "omt_a");
  2478. await send("/disable");
  2479. await service.watchAutomationRun({
  2480. workspacePath: "/tmp/workspace",
  2481. taskId: "scheduled-task",
  2482. target: {
  2483. provider: "feishu",
  2484. botId: "feishu-1",
  2485. providerUserId: "oc_a",
  2486. chatType: "group",
  2487. threadId: "omt_a",
  2488. rootMessageId: "root_omt_a",
  2489. },
  2490. });
  2491. expect(taskService.onDynamicTaskEvent).not.toHaveBeenCalled();
  2492. });
  2493. it("does not attach an automation delivery watcher to a disabled group", async () => {
  2494. const { send, service, taskService } = setup();
  2495. taskService.onDynamicTaskEvent = vi.fn(() => () => ({ dispose() {} })) as never;
  2496. await send("/enable");
  2497. await send("/disable");
  2498. await service.watchAutomationRun({
  2499. workspacePath: "/tmp/workspace",
  2500. taskId: "scheduled-task",
  2501. target: { provider: "feishu", botId: "feishu-1", providerUserId: "oc_a", chatType: "group" },
  2502. });
  2503. expect(taskService.onDynamicTaskEvent).not.toHaveBeenCalled();
  2504. });
  2505. });