botsService.groups.test.ts 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578
  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. });
  1196. it("keeps quoted text separate from real file and image attachments", async () => {
  1197. const { send, service, taskService } = setup();
  1198. await send("/enable");
  1199. await service.handleInboundMessage({
  1200. botId: "feishu-1",
  1201. text: "inspect these",
  1202. referencedMessage: { messageId: "om_quote_file", text: "original line\nsecond line" },
  1203. attachments: [
  1204. {
  1205. id: "file",
  1206. kind: "file",
  1207. filename: "reference.txt",
  1208. mimeType: "text/plain",
  1209. sizeBytes: 4,
  1210. dataBase64: "dGVzdA==",
  1211. },
  1212. {
  1213. id: "image",
  1214. kind: "image",
  1215. filename: "reference.png",
  1216. mimeType: "image/png",
  1217. sizeBytes: 4,
  1218. dataBase64: "dGVzdA==",
  1219. },
  1220. ],
  1221. actor: {
  1222. botId: "feishu-1",
  1223. provider: "feishu",
  1224. chatType: "group",
  1225. chatId: "oc_a",
  1226. providerUserId: "ou_user",
  1227. providerMessageId: "om_quote_with_materials",
  1228. },
  1229. });
  1230. const admitted = taskService.submitBotGroupInput.mock.calls[0]![0];
  1231. expect(admitted.content).toBe("inspect these");
  1232. expect(admitted.conversationQuotes).toEqual([
  1233. expect.objectContaining({ text: "original line\nsecond line" }),
  1234. ]);
  1235. expect(admitted.attachments).toEqual([
  1236. expect.objectContaining({ kind: "file", filename: "reference.txt", dataBase64: "dGVzdA==" }),
  1237. expect.objectContaining({ kind: "image", filename: "reference.png", dataBase64: "dGVzdA==" }),
  1238. ]);
  1239. });
  1240. it.each([1, 5])(
  1241. "rejects unavailable or excessive group attachments atomically (%s)",
  1242. async (count) => {
  1243. const { send, service, taskService } = setup();
  1244. await send("/enable");
  1245. await service.handleInboundMessage({
  1246. botId: "feishu-1",
  1247. text: "do not execute incomplete input",
  1248. attachments: Array.from({ length: count }, (_, i) => ({
  1249. id: `file-${i}`,
  1250. kind: "file" as const,
  1251. filename: "missing.txt",
  1252. mimeType: "text/plain",
  1253. sizeBytes: 4,
  1254. ...(count > 1 ? { dataBase64: "dGVzdA==" } : {}),
  1255. })),
  1256. actor: {
  1257. botId: "feishu-1",
  1258. provider: "feishu",
  1259. chatType: "group",
  1260. chatId: "oc_a",
  1261. providerUserId: "ou_user",
  1262. providerMessageId: `om_missing_${count}`,
  1263. },
  1264. });
  1265. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1266. expect(taskService.createTask).not.toHaveBeenCalled();
  1267. },
  1268. );
  1269. it("rejects oversized explicit quotations before creating or admitting a task", async () => {
  1270. const { send, service, taskService } = setup();
  1271. await send("/enable");
  1272. const replies = await service.handleInboundMessage({
  1273. botId: "feishu-1",
  1274. text: "summarize",
  1275. referencedMessage: { messageId: "om_large_quote", text: "a".repeat(8001) },
  1276. actor: {
  1277. botId: "feishu-1",
  1278. provider: "feishu",
  1279. chatType: "group",
  1280. chatId: "oc_a",
  1281. providerUserId: "ou_user",
  1282. providerMessageId: "om_large_request",
  1283. },
  1284. });
  1285. expect(replies.length).toBeGreaterThan(0);
  1286. expect(taskService.createTask).not.toHaveBeenCalled();
  1287. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1288. });
  1289. it("blocks explicitly disabled history before task creation", async () => {
  1290. const { send, taskService } = setup();
  1291. await send("/enable");
  1292. await send("/history off");
  1293. const replies = await send("hello", "oc_a", "ou_user", "omt_off");
  1294. expect(historyMock).not.toHaveBeenCalled();
  1295. expect(taskService.createTask).not.toHaveBeenCalled();
  1296. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1297. expect(replies[0]?.text).toContain("/history on");
  1298. expect(replies[0]?.mentionedUserIds).toEqual(["ou_user"]);
  1299. });
  1300. it("guides the administrator without admission on missing history permission", async () => {
  1301. const { send, taskService } = setup();
  1302. await send("/enable");
  1303. historyMock.mockRejectedValueOnce(new TopicHistoryPermissionError("Access denied"));
  1304. const replies = await send("hello", "oc_a", "ou_user", "omt_permission");
  1305. expect(replies[0]?.text).toContain("im:message.group_msg");
  1306. expect(replies[0]?.text).toContain("https://open.feishu.cn/app");
  1307. expect(taskService.createTask).not.toHaveBeenCalled();
  1308. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1309. await send("retry", "oc_a", "ou_user", "omt_permission");
  1310. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1311. });
  1312. it("reads topic history by default and blocks a failed read before task creation", async () => {
  1313. const { send, taskService } = setup();
  1314. await send("/enable");
  1315. historyMock.mockRejectedValueOnce(new Error("network unavailable"));
  1316. const replies = await send("hello", "oc_a", "ou_user", "omt_error");
  1317. expect(historyMock).toHaveBeenCalledOnce();
  1318. expect(taskService.createTask).not.toHaveBeenCalled();
  1319. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1320. expect(replies[0]?.text).toMatch(/retry|重试/);
  1321. expect((reactionMock.mock.lastCall as unknown[] | undefined)?.[2]).toBe("failed");
  1322. });
  1323. it("uses available opted-in topic discussion for a bare mention", async () => {
  1324. const { send, taskService } = setup();
  1325. await send("/enable");
  1326. await send("/history on");
  1327. historyMock.mockResolvedValueOnce({
  1328. messages: [
  1329. {
  1330. id: "om_background",
  1331. chatId: "oc_a",
  1332. threadId: "omt_empty",
  1333. senderId: "ou_user",
  1334. senderType: "user",
  1335. text: "What is two plus two",
  1336. createdAt: 1,
  1337. kind: "text",
  1338. },
  1339. ] as never[],
  1340. checkpoint: "om__ou_user",
  1341. hasGap: false,
  1342. });
  1343. await send("", "oc_a", "ou_user", "omt_empty");
  1344. const input = taskService.submitBotGroupInput.mock.calls[0]![0];
  1345. expect(input.content).toBe("");
  1346. expect(input.attachments).toEqual([
  1347. expect.objectContaining({
  1348. kind: "file",
  1349. sourceKind: "topic-history",
  1350. mimeType: "text/plain",
  1351. textContent: expect.stringContaining("What is two plus two"),
  1352. }),
  1353. ]);
  1354. expect(input.attachments[0].textContent).toContain("ou_user");
  1355. expect(input.source.topicContext).toBeUndefined();
  1356. expect(JSON.stringify(input.source)).not.toContain("What is two plus two");
  1357. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1358. expect(taskService.submitBotGroupInput).toHaveBeenCalledWith(
  1359. expect.objectContaining({
  1360. source: expect.objectContaining({
  1361. topicHistory: expect.objectContaining({ checkpoint: "om__ou_user", messageCount: 1 }),
  1362. }),
  1363. }),
  1364. );
  1365. });
  1366. it("rejects a bare mention when opted-in history is unavailable", async () => {
  1367. const { send, taskService } = setup();
  1368. await send("/enable");
  1369. await send("/history on");
  1370. historyMock.mockRejectedValueOnce(new Error("history unavailable"));
  1371. expect((await send("", "oc_a", "ou_user", "omt_empty"))[0]?.text).toContain("重试");
  1372. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1373. });
  1374. it("keeps the last successful checkpoint when a history read is rejected", async () => {
  1375. const { send, taskService } = setup();
  1376. await send("/enable");
  1377. await send("/history on");
  1378. historyMock.mockResolvedValueOnce({
  1379. messages: [],
  1380. checkpoint: "om_first_ou_user",
  1381. hasGap: false,
  1382. });
  1383. await send("first", "oc_a", "ou_user", "omt_gap");
  1384. await send("/history on");
  1385. historyMock.mockRejectedValueOnce(new Error("history unavailable"));
  1386. await send("second", "oc_a", "ou_user", "omt_gap");
  1387. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1388. await send("third", "oc_a", "ou_user", "omt_gap");
  1389. expect(historyMock.mock.calls.at(-1)?.[1].checkpoint).toBe("om_first_ou_user");
  1390. });
  1391. it("preserves a history opt-in while an earlier input admission finishes", async () => {
  1392. const { send, repo, taskService } = setup();
  1393. await send("/enable");
  1394. const original = taskService.submitBotGroupInput!;
  1395. let release!: () => void;
  1396. let started!: () => void;
  1397. const ready = new Promise<void>((resolve) => {
  1398. started = resolve;
  1399. });
  1400. taskService.submitBotGroupInput = vi.fn(async (params) => {
  1401. started();
  1402. await new Promise<void>((resolve) => {
  1403. release = resolve;
  1404. });
  1405. return original(params);
  1406. });
  1407. const pending = send("work");
  1408. await ready;
  1409. await send("/history on", "oc_a", "ou_user", "omt_settings");
  1410. release();
  1411. await pending;
  1412. expect(
  1413. (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a"])]?.group?.historyEnabled,
  1414. ).toBe(true);
  1415. });
  1416. it("rejects admission if the group is disabled during topic history preparation", async () => {
  1417. const { send, taskService } = setup();
  1418. await send("/enable");
  1419. await send("/history on");
  1420. let release!: () => void;
  1421. let started!: () => void;
  1422. const ready = new Promise<void>((resolve) => {
  1423. started = resolve;
  1424. });
  1425. historyMock.mockImplementationOnce(async (_bot, request) => {
  1426. started();
  1427. await new Promise<void>((resolve) => {
  1428. release = resolve;
  1429. });
  1430. return { messages: [], checkpoint: request.messageId, hasGap: false };
  1431. });
  1432. const pending = send("pending history", "oc_a", "ou_user", "omt_race");
  1433. await ready;
  1434. await send("/disable");
  1435. release();
  1436. expect(await pending).toEqual([]);
  1437. await new Promise((resolve) => setTimeout(resolve, 0));
  1438. expect(taskService.createTask).not.toHaveBeenCalled();
  1439. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  1440. });
  1441. it("scopes topic details to the bound task and workspace", async () => {
  1442. const { send, service, repo, taskService } = setup();
  1443. await send("/enable");
  1444. await send("topic request", "oc_a", "ou_user", "thread-a");
  1445. const state = (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a", "thread-a"])]!;
  1446. taskService.readBotTopicSummaries = vi.fn(async () => [
  1447. { checkpoint: "m1", text: "Decision: blue" },
  1448. ]);
  1449. const params = {
  1450. botId: "feishu-1",
  1451. chatId: "oc_a",
  1452. threadId: "thread-a",
  1453. taskId: state.activeTaskId!,
  1454. workspacePath: state.workspacePath!,
  1455. workspaceIdentity: state.workspaceIdentity,
  1456. };
  1457. expect(await service.getTopicDetails!(params)).toMatchObject({
  1458. summaries: [{ checkpoint: "m1", text: "Decision: blue" }],
  1459. messageCount: 0,
  1460. });
  1461. await expect(service.getTopicDetails!({ ...params, taskId: "unrelated" })).rejects.toThrow(
  1462. /scope/,
  1463. );
  1464. await expect(
  1465. service.getTopicDetails!({ ...params, workspaceIdentity: "ssh://other" }),
  1466. ).rejects.toThrow(/scope/);
  1467. });
  1468. it.each([false, true])(
  1469. "isolates reply topics and migrates old aliases once (legacy=%s)",
  1470. async (legacy) => {
  1471. const { send, repo, taskService } = setup(true);
  1472. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  1473. taskService.renameTask = vi.fn(async () => ({ taskId: "topic-task-1" }) as never);
  1474. await send("/enable");
  1475. const state = await repo.readState();
  1476. const key = JSON.stringify(["feishu-1", "oc_a"]);
  1477. state.bots[key]!.activeTaskId = "original-task";
  1478. state.bots[key]!.mode = "task";
  1479. state.bots[key]!.group!.taskIds = ["original-task"];
  1480. state.bots[key]!.group!.deliveries = {
  1481. result: {
  1482. id: "result",
  1483. taskId: "original-task",
  1484. text: "reply",
  1485. status: "sent",
  1486. updatedAt: 1,
  1487. providerMessageId: "root_omt_reply",
  1488. },
  1489. };
  1490. await repo.writeState(state);
  1491. if (legacy) {
  1492. state.bots[key]!.group!.topicAliases = {
  1493. omt_reply: { taskId: "original-task", rootMessageId: "root_omt_reply" },
  1494. };
  1495. state.bots[key]!.group!.taskWorkspaces = {
  1496. "original-task": { workspacePath: "/old-workspace", workspaceIdentity: "old-identity" },
  1497. };
  1498. await repo.writeState(state);
  1499. }
  1500. await send("first reply", "oc_a", "ou_user", "omt_reply");
  1501. await send("second reply", "oc_a", "ou_user", "omt_reply");
  1502. const after = await repo.readState();
  1503. const topic = after.bots[JSON.stringify(["feishu-1", "oc_a", "omt_reply"])];
  1504. expect(topic?.activeTaskId).toBe("topic-task-1");
  1505. expect(taskService.createTask).toHaveBeenCalledOnce();
  1506. if (legacy)
  1507. expect(taskService.getBotGroupTaskBlockReason).toHaveBeenCalledWith({
  1508. taskId: "original-task",
  1509. workspacePath: "/old-workspace",
  1510. workspaceIdentity: "old-identity",
  1511. });
  1512. expect(after.bots[key]?.group?.topicAliases?.omt_reply).toBeUndefined();
  1513. expect(taskService.renameTask).toHaveBeenCalledWith(
  1514. expect.objectContaining({ title: "飞书 · 测试群 · omt_reply" }),
  1515. );
  1516. expect(taskService.submitBotGroupInput.mock.calls.map(([input]) => input.taskId)).toEqual([
  1517. "topic-task-1",
  1518. "topic-task-1",
  1519. ]);
  1520. expect(after.bots[key]?.activeTaskId).toBe("original-task");
  1521. const [reply] = await send("/new", "oc_a", "ou_user", "omt_reply");
  1522. expect(reply.text).toMatch(/another topic|另开/);
  1523. },
  1524. );
  1525. it("reads history only on entry or explicit reconciliation and keeps the accepted checkpoint", async () => {
  1526. const { send, taskService } = setup();
  1527. await send("/enable");
  1528. await send("first", "oc_a", "ou_user", "omt_a");
  1529. expect(historyMock).toHaveBeenCalledOnce();
  1530. await send("/history on");
  1531. await send("second", "oc_a", "ou_user", "omt_a");
  1532. expect(historyMock).toHaveBeenLastCalledWith(
  1533. expect.anything(),
  1534. expect.objectContaining({
  1535. messageId: "om_second_ou_user",
  1536. checkpoint: "om_first_ou_user",
  1537. }),
  1538. );
  1539. await send("third", "oc_a", "ou_user", "omt_a");
  1540. expect(historyMock).toHaveBeenCalledTimes(2);
  1541. expect(
  1542. taskService.submitBotGroupInput.mock.calls.at(-1)?.[0].source.topicHistory,
  1543. ).toBeUndefined();
  1544. await send("/leave", "oc_a", "ou_user", "omt_a");
  1545. await send("resume", "oc_a", "ou_user", "omt_a");
  1546. expect(historyMock).toHaveBeenLastCalledWith(
  1547. expect.anything(),
  1548. expect.objectContaining({ checkpoint: "om_third_ou_user" }),
  1549. );
  1550. });
  1551. it("keeps history off until the owner explicitly enables it for the group", async () => {
  1552. const { send, repo } = setup();
  1553. await send("/enable");
  1554. const key = JSON.stringify(["feishu-1", "oc_a"]);
  1555. expect((await repo.readState()).bots[key]?.group?.historyEnabled).toBeFalsy();
  1556. await send("/history on", "oc_a", "member");
  1557. expect((await repo.readState()).bots[key]?.group?.historyEnabled).toBeFalsy();
  1558. await send("/history on", "oc_a", "ou_user", "omt_a");
  1559. expect((await repo.readState()).bots[key]?.group?.historyEnabled).toBe(true);
  1560. await send("/history off");
  1561. expect((await repo.readState()).bots[key]?.group?.historyEnabled).toBe(false);
  1562. });
  1563. it("carries topic identity through admission without a legacy queue card", async () => {
  1564. const { send, taskService, repo } = setup();
  1565. await send("/enable");
  1566. const [reply] = await send("topic request", "oc_a", "ou_user", "omt_a");
  1567. expect(taskService.submitBotGroupInput).toHaveBeenCalledWith(
  1568. expect.objectContaining({
  1569. source: expect.objectContaining({
  1570. threadId: "omt_a",
  1571. authorizationId: (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a"])]!
  1572. .group!.authorizationId,
  1573. }),
  1574. }),
  1575. );
  1576. expect(reply).toBeUndefined();
  1577. const [newReply] = await send("/new", "oc_a", "ou_user", "omt_a");
  1578. expect(newReply.text).toMatch(/another topic|另开/);
  1579. });
  1580. it("creates independent topic drafts from group defaults and keeps the default draft", async () => {
  1581. const { send, repo } = setup();
  1582. await send("/enable");
  1583. await send("/status", "oc_a", "ou_user", "omt_a");
  1584. await send("/status", "oc_a", "ou_user", "omt_b");
  1585. const { bots } = await repo.readState();
  1586. const a = bots[JSON.stringify(["feishu-1", "oc_a", "omt_a"])];
  1587. const b = bots[JSON.stringify(["feishu-1", "oc_a", "omt_b"])];
  1588. expect(a?.group?.threadId).toBe("omt_a");
  1589. expect(b?.group?.threadId).toBe("omt_b");
  1590. expect(a?.draftOptions?.mode).toBe("default");
  1591. expect(a?.group?.inputs).toBeUndefined();
  1592. expect(bots[JSON.stringify(["feishu-1", "oc_a"])].group?.threadId).toBeUndefined();
  1593. });
  1594. it("disables the entire group from a topic and invalidates sibling authorization", async () => {
  1595. const { send, repo } = setup();
  1596. await send("/enable");
  1597. await send("/status", "oc_a", "ou_user", "omt_a");
  1598. await send("/status", "oc_a", "ou_user", "omt_b");
  1599. await send("/disable", "oc_a", "ou_user", "omt_a");
  1600. const groups = Object.values((await repo.readState()).bots).filter((s) => s.group);
  1601. expect(groups).toHaveLength(3);
  1602. expect(groups.every((s) => s.group?.enabled === false)).toBe(true);
  1603. const [reply] = await send("/status", "oc_a", "member", "omt_b");
  1604. expect(reply?.text).toMatch(/not enabled|未启用/i);
  1605. });
  1606. it.each([undefined, "omt_fast"])(
  1607. "keeps completed progress and reaction before admission returns (%s)",
  1608. async (threadId) => {
  1609. const { send, taskService, repo } = setup();
  1610. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1611. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1612. emit = listener;
  1613. return { dispose: vi.fn() };
  1614. });
  1615. taskService.submitBotGroupInput = vi.fn(async (params) => {
  1616. await emit({
  1617. type: "task_run_started",
  1618. taskId: params.taskId,
  1619. inputId: params.commandId,
  1620. } as Parameters<typeof emit>[0]);
  1621. await emit({
  1622. type: "task_complete",
  1623. taskId: params.taskId,
  1624. inputId: params.commandId,
  1625. stopReason: "end_turn",
  1626. } as Parameters<typeof emit>[0]);
  1627. return {
  1628. commandId: params.commandId,
  1629. status: "accepted",
  1630. revisionAtDecision: 1,
  1631. result: { type: "inputAccepted", inputId: params.commandId, delivery: "queue" },
  1632. };
  1633. });
  1634. await send("/enable");
  1635. await send("fast completion", "oc_a", "ou_user", threadId);
  1636. const context = Object.values((await repo.readState()).bots).find(
  1637. (value) => value.group?.inputs,
  1638. )!;
  1639. const input = Object.values(context.group!.inputs!)[0]!;
  1640. expect(input.admission).toBe("accepted");
  1641. expect(input.progress?.status).toBe("done");
  1642. expect((reactionMock.mock.lastCall as unknown[] | undefined)?.[2]).toBe("done");
  1643. },
  1644. );
  1645. it.each(["task_complete", "task_error"] as const)(
  1646. "projects %s onto the original input reaction",
  1647. async (type) => {
  1648. const { send, taskService, repo } = setup();
  1649. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1650. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1651. emit = listener;
  1652. return { dispose: vi.fn() };
  1653. });
  1654. await send("/enable");
  1655. await send("reaction result", "oc_a", "ou_member");
  1656. const context = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  1657. const [inputId, input] = Object.entries(context.group!.inputs!)[0]!;
  1658. const saved = await repo.readState();
  1659. const savedContext = Object.values(saved.bots).find((value) => value.group)!;
  1660. savedContext.group!.inputs![inputId]!.progress = {
  1661. status: "waiting",
  1662. cardMessageId: "om_queue_card",
  1663. cardStatus: "waiting",
  1664. };
  1665. await repo.writeState(saved);
  1666. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1667. typeof emit
  1668. >[0]);
  1669. await emit({
  1670. type,
  1671. taskId: context.activeTaskId!,
  1672. inputId,
  1673. stopReason: "end_turn",
  1674. error: "test failure",
  1675. } as Parameters<typeof emit>[0]);
  1676. const last = reactionMock.mock.lastCall as unknown[] | undefined;
  1677. expect(last?.[1]).toBe(input.source.messageId);
  1678. expect(last?.[2]).toBe(type === "task_error" ? "failed" : "done");
  1679. const cardCalls = cardUpdateMock.mock.calls as unknown as Array<
  1680. [unknown, { providerMessageId: string }, { text: string; selection?: unknown }]
  1681. >;
  1682. expect(cardCalls.map((call) => call[1].providerMessageId)).toEqual([
  1683. "om_queue_card",
  1684. "om_queue_card",
  1685. ]);
  1686. expect(cardCalls.map((call) => call[2].text)).toEqual([
  1687. "正在执行",
  1688. type === "task_error" ? "执行失败" : "已完成",
  1689. ]);
  1690. expect(cardCalls.every((call) => call[2].selection === undefined)).toBe(true);
  1691. },
  1692. );
  1693. it.each(["task_complete", "turn_steer_status"])(
  1694. "does not send old topic queue or stop notices for %s",
  1695. async (type) => {
  1696. const { send, taskService, repo } = setup();
  1697. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1698. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1699. emit = listener;
  1700. return { dispose: vi.fn() };
  1701. });
  1702. await send("/enable");
  1703. await send("topic input", "oc_a", "ou_user", "omt_notices");
  1704. const key = JSON.stringify(["feishu-1", "oc_a", "omt_notices"]);
  1705. const context = (await repo.readState()).bots[key]!;
  1706. const inputId = Object.keys(context.group!.inputs!)[0]!;
  1707. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1708. typeof emit
  1709. >[0]);
  1710. await emit({
  1711. type,
  1712. taskId: context.activeTaskId!,
  1713. inputId,
  1714. stopReason: "cancelled",
  1715. status: "discarded",
  1716. reason: "session_resumed",
  1717. pendingInputIds: [inputId],
  1718. } as Parameters<typeof emit>[0]);
  1719. expect(Object.values((await repo.readState()).bots[key]!.group!.deliveries ?? {})).toEqual(
  1720. [],
  1721. );
  1722. expect((reactionMock.mock.calls.at(-1) as unknown[] | undefined)?.[2]).toBe("cancelled");
  1723. expect((await repo.readState()).bots[key]!.group!.inputs![inputId]!.progress?.status).toBe(
  1724. type === "task_complete" ? "stopped" : "discarded",
  1725. );
  1726. },
  1727. );
  1728. it.each(["Alice", "ou_member"])(
  1729. "keeps stopped group runs silent while updating reactions (%s)",
  1730. async (senderName) => {
  1731. const { send, taskService, repo } = setup();
  1732. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1733. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1734. emit = listener;
  1735. return { dispose: vi.fn() };
  1736. });
  1737. await send("/enable");
  1738. await send("hello", "oc_a", "ou_member");
  1739. const state = await repo.readState();
  1740. const context = Object.values(state.bots).find((value) => value.group)!;
  1741. const [inputId, input] = Object.entries(context.group!.inputs!)[0]!;
  1742. input.source.senderName = senderName;
  1743. await repo.writeState(state);
  1744. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1745. typeof emit
  1746. >[0]);
  1747. await emit({
  1748. type: "task_complete",
  1749. taskId: context.activeTaskId!,
  1750. inputId,
  1751. stopReason: "cancelled",
  1752. } as Parameters<typeof emit>[0]);
  1753. const updated = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  1754. expect(Object.values(updated.group!.deliveries ?? {})).toEqual([]);
  1755. expect(reactionMock.mock.calls.map((call) => (call as unknown[])[2])).toEqual([
  1756. "waiting",
  1757. "working",
  1758. "cancelled",
  1759. ]);
  1760. },
  1761. );
  1762. it("keeps each run's reply target when another member speaks and clears it for desktop runs", async () => {
  1763. const { send, taskService, repo } = setup();
  1764. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1765. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1766. emit = listener;
  1767. return { dispose: vi.fn() };
  1768. });
  1769. await send("/enable");
  1770. await send("first", "oc_a", "ou_alice");
  1771. await send("second", "oc_a", "ou_bob");
  1772. const context = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  1773. const inputs = Object.entries(context.group!.inputs!);
  1774. expect(inputs).toHaveLength(2);
  1775. for (const [inputId] of [...inputs, ["desktop-run", undefined]]) {
  1776. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1777. typeof emit
  1778. >[0]);
  1779. await emit({
  1780. type: "task_complete",
  1781. taskId: context.activeTaskId!,
  1782. inputId,
  1783. stopReason: "error",
  1784. error: "example failure",
  1785. } as Parameters<typeof emit>[0]);
  1786. }
  1787. const updated = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  1788. const results = Object.values(updated.group!.deliveries!);
  1789. expect(results).toHaveLength(3);
  1790. for (const [index, [, input]] of inputs.entries()) {
  1791. expect(results[index]).toMatchObject({
  1792. replyToMessageId: input.source.messageId,
  1793. mentionedUserIds: [input.source.senderId],
  1794. });
  1795. }
  1796. expect(results[2]?.replyToMessageId).toBeUndefined();
  1797. expect(results[2]?.mentionedUserIds).toBeUndefined();
  1798. });
  1799. it("quotes the batch boundary and mentions deduplicated participants only on the first saved part", async () => {
  1800. const { send, taskService, repo } = setup();
  1801. let emit!: Parameters<ReturnType<typeof taskService.onDynamicTaskEvent>>[0];
  1802. taskService.onDynamicTaskEvent = vi.fn(() => (listener) => {
  1803. emit = listener;
  1804. return { dispose: vi.fn() };
  1805. });
  1806. await send("/enable");
  1807. await send("batch", "oc_a", "ou_bob", "omt_batch");
  1808. const state = await repo.readState();
  1809. const context = Object.values(state.bots).find(
  1810. (value) => value.group?.threadId === "omt_batch",
  1811. )!;
  1812. const [inputId, input] = Object.entries(context.group!.inputs!)[0]!;
  1813. input.source.messages = [
  1814. {
  1815. messageId: "om_first",
  1816. senderId: "ou_alice",
  1817. senderName: "Alice",
  1818. mentionedBot: true,
  1819. text: "first",
  1820. attachmentIndexes: [],
  1821. },
  1822. {
  1823. messageId: "om_next",
  1824. senderId: "ou_alice",
  1825. senderName: "Alice",
  1826. text: "next",
  1827. attachmentIndexes: [],
  1828. },
  1829. {
  1830. messageId: input.source.messageId,
  1831. senderId: "ou_bob",
  1832. senderName: "Bob",
  1833. text: "last",
  1834. attachmentIndexes: [],
  1835. },
  1836. ];
  1837. await repo.writeState(state);
  1838. await emit({ type: "task_run_started", taskId: context.activeTaskId!, inputId } as Parameters<
  1839. typeof emit
  1840. >[0]);
  1841. await emit({
  1842. type: "task_error",
  1843. taskId: context.activeTaskId!,
  1844. inputId,
  1845. error: "错误详情".repeat(1100),
  1846. } as Parameters<typeof emit>[0]);
  1847. const updated = Object.values((await repo.readState()).bots).find(
  1848. (value) => value.group?.threadId === "omt_batch",
  1849. )!;
  1850. const results = Object.values(updated.group!.deliveries!);
  1851. expect(results.length).toBeGreaterThan(1);
  1852. for (const [index, result] of results.entries()) {
  1853. expect(result.replyToMessageId).toBe(input.source.messageId);
  1854. expect(result.threadId).toBe("omt_batch");
  1855. expect(result.mentionedUserIds).toEqual(index === 0 ? ["ou_alice"] : undefined);
  1856. }
  1857. });
  1858. it("reads names only for an enabled authorized group", async () => {
  1859. const { send, service } = setup();
  1860. const params = { botId: "feishu-1", chatId: "oc_a" };
  1861. await expect(service.getGroupMemberNames!(params)).rejects.toThrow();
  1862. await send("/enable");
  1863. expect(await service.getGroupMemberNames!(params)).toEqual({ ou_user: "Alice" });
  1864. await expect(service.getGroupMemberNames!({ ...params, chatId: "oc_other" })).rejects.toThrow();
  1865. await send("/disable");
  1866. await expect(service.getGroupMemberNames!(params)).rejects.toThrow();
  1867. });
  1868. it("rejects a directory response after the group is disabled during lookup", async () => {
  1869. const { send, service } = setup();
  1870. await send("/enable");
  1871. let finish!: (names: Record<string, string>) => void;
  1872. directoryMock.mockImplementationOnce(
  1873. () =>
  1874. new Promise((resolve) => {
  1875. finish = resolve;
  1876. }),
  1877. );
  1878. const reading = service.getGroupMemberNames!({ botId: "feishu-1", chatId: "oc_a" });
  1879. const rejection = expect(reading).rejects.toThrow("unavailable");
  1880. await vi.waitFor(() => expect(directoryMock).toHaveBeenCalledTimes(1));
  1881. await send("/disable");
  1882. finish({ ou_user: "Alice" });
  1883. await rejection;
  1884. });
  1885. it("reconciles only saved unknown results in the currently authorized group", async () => {
  1886. const { send, service, repo } = setup();
  1887. await send("/enable");
  1888. await send("work", "oc_a", "member");
  1889. const state = await repo.readState();
  1890. const context = Object.values(state.bots).find((value) => value.group)!;
  1891. context.group!.deliveries = {
  1892. unknown: {
  1893. id: "unknown",
  1894. taskId: context.activeTaskId!,
  1895. text: "saved",
  1896. status: "unknown",
  1897. updatedAt: 1,
  1898. },
  1899. };
  1900. await repo.writeState(state);
  1901. expect(
  1902. await service.reconcileGroupResult({
  1903. botId: "feishu-1",
  1904. chatId: "oc_a",
  1905. deliveryId: "unknown",
  1906. received: true,
  1907. }),
  1908. ).toMatchObject({ status: "sent", text: "saved" });
  1909. await expect(
  1910. service.reconcileGroupResult({
  1911. botId: "feishu-1",
  1912. chatId: "oc_a",
  1913. deliveryId: "unknown",
  1914. received: false,
  1915. }),
  1916. ).rejects.toThrow();
  1917. context.group!.deliveries!.unknown!.status = "unknown";
  1918. await send("/disable");
  1919. await expect(
  1920. service.reconcileGroupResult({
  1921. botId: "feishu-1",
  1922. chatId: "oc_a",
  1923. deliveryId: "unknown",
  1924. received: false,
  1925. }),
  1926. ).rejects.toThrow();
  1927. });
  1928. it("refuses to resend a saved result from an earlier authorization generation", async () => {
  1929. const { send, service, repo } = setup();
  1930. await send("/enable");
  1931. await send("work", "oc_a", "member");
  1932. const state = await repo.readState();
  1933. const context = Object.values(state.bots).find((value) => value.group)!;
  1934. context.group!.deliveries = {
  1935. old: {
  1936. id: "old",
  1937. taskId: context.activeTaskId!,
  1938. text: "old",
  1939. status: "failed",
  1940. authorizationId: "earlier-generation",
  1941. updatedAt: 1,
  1942. },
  1943. };
  1944. await repo.writeState(state);
  1945. expect(
  1946. await service.resendGroupResult({ botId: "feishu-1", chatId: "oc_a", deliveryId: "old" }),
  1947. ).toMatchObject({ status: "invalidated" });
  1948. });
  1949. it("requires owner activation, keeps private state and two groups independent", async () => {
  1950. const { service, send, repo } = setup();
  1951. expect((await send("/enable", "oc_a", "member"))[0]?.text).toContain("绑定");
  1952. expect((await service.getBotStates()).filter((s) => s.group)).toHaveLength(0);
  1953. await service.handleInboundMessage({
  1954. botId: "feishu-1",
  1955. actor: {
  1956. provider: "feishu",
  1957. botId: "feishu-1",
  1958. providerUserId: "ou_user",
  1959. chatType: "private",
  1960. },
  1961. text: "/status",
  1962. });
  1963. await send("/enable");
  1964. await send("/enable", "oc_b");
  1965. const groups = (await service.getBotStates()).filter((s) => s.group);
  1966. expect(groups).toHaveLength(2);
  1967. expect(groups.map((s) => s.group?.chatId).sort()).toEqual(["oc_a", "oc_b"]);
  1968. expect(groups.every((s) => s.draftOptions?.mode === "default")).toBe(true);
  1969. const before = structuredClone(await repo.readState());
  1970. await send("/enable");
  1971. expect(await repo.readState()).toEqual(before);
  1972. const memberStatus = await send("/status", "oc_a", "member");
  1973. expect(memberStatus[0]?.providerUserId).toBe("oc_a");
  1974. expect(memberStatus.map((r) => r.text).join("\n")).not.toContain("/tmp/workspace");
  1975. expect((await send("/new", "oc_a", "member"))[0]?.text).toContain("绑定");
  1976. });
  1977. it("disables only the selected group and re-enables without resetting it", async () => {
  1978. const { service, send } = setup();
  1979. await send("/enable");
  1980. await send("/enable", "oc_b");
  1981. await send("/disable");
  1982. let states = await service.getBotStates();
  1983. expect(states.find((s) => s.group?.chatId === "oc_a")?.group?.enabled).toBe(false);
  1984. expect(states.find((s) => s.group?.chatId === "oc_b")?.group?.enabled).toBe(true);
  1985. expect((await send("hello", "oc_a", "member"))[0]?.text).toContain("启用");
  1986. await send("/enable");
  1987. states = await service.getBotStates();
  1988. expect(states.find((s) => s.group?.chatId === "oc_a")?.group?.enabled).toBe(true);
  1989. });
  1990. it("does not readmit an accepted or uncertain provider message after in-memory dedupe is gone", async () => {
  1991. const { send, taskService } = setup();
  1992. await send("/enable");
  1993. await send("accepted-once", "oc_a", "member");
  1994. await send("accepted-once", "oc_a", "member");
  1995. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  1996. vi.mocked(taskService.submitBotGroupInput).mockRejectedValueOnce(
  1997. new Error("lost acknowledgement"),
  1998. );
  1999. await expect(send("uncertain-once", "oc_a", "member")).rejects.toThrow("lost acknowledgement");
  2000. const retry = await send("uncertain-once", "oc_a", "member");
  2001. expect(retry[0]?.text).toContain("核对");
  2002. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  2003. });
  2004. it("admits member inputs through the canonical queue without legacy send or yolo", async () => {
  2005. const { send, taskService } = setup();
  2006. await send("/enable");
  2007. expect((await send("first", "oc_a", "member"))[0]?.text).toContain("等待执行");
  2008. expect((await send("second", "oc_a", "other"))[0]?.text).toContain("等待执行");
  2009. expect(taskService.createTask).toHaveBeenCalledTimes(1);
  2010. expect(taskService.createTask).toHaveBeenCalledWith(
  2011. expect.objectContaining({ permissionScope: "session" }),
  2012. );
  2013. expect(taskService.sendPrompt).not.toHaveBeenCalled();
  2014. expect(taskService.submitBotGroupInput).toHaveBeenCalledTimes(2);
  2015. expect(taskService.submitBotGroupInput).toHaveBeenLastCalledWith(
  2016. expect.objectContaining({
  2017. source: expect.objectContaining({
  2018. chatId: "oc_a",
  2019. senderId: "other",
  2020. messageId: "om_second_other",
  2021. }),
  2022. }),
  2023. );
  2024. expect(taskService.setMode).toHaveBeenCalledWith(expect.objectContaining({ mode: "default" }));
  2025. });
  2026. it("does not resolve another group's task through the direct snapshot fallback", async () => {
  2027. const { send, taskService } = setup();
  2028. await send("/enable");
  2029. await send("/task foreign-task");
  2030. expect(taskService.getTaskSnapshot).not.toHaveBeenCalledWith(
  2031. expect.objectContaining({ taskId: "foreign-task" }),
  2032. );
  2033. });
  2034. it("does not expose the local absolute workspace path in group status", async () => {
  2035. const { send, service } = setup();
  2036. await send("/enable");
  2037. const path = (await service.getBotStates()).find((state) => state.group)!.workspacePath;
  2038. expect(path.startsWith("/")).toBe(true);
  2039. expect((await send("/status", "oc_a", "member"))[0]!.text).not.toContain(path);
  2040. });
  2041. it("inherits structured task selection into a topic instead of parsing its display model", async () => {
  2042. const { send, taskService, repo } = setup(true);
  2043. await send("/enable");
  2044. await send("parent");
  2045. const parent = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  2046. taskService.listTasks = vi.fn(async () => [
  2047. {
  2048. taskId: parent.activeTaskId!,
  2049. provider: "glm",
  2050. model: "glm/default$max",
  2051. title: "Parent",
  2052. workspacePath: "/tmp/workspace",
  2053. },
  2054. ]) as typeof taskService.listTasks;
  2055. taskService.getTaskModelSelection = vi.fn(async () => ({
  2056. providerId: "glm",
  2057. modelId: "default",
  2058. options: { reasoningLevel: "max" },
  2059. }));
  2060. await send("topic", "oc_a", "ou_user", "omt_selection");
  2061. const topic = Object.values((await repo.readState()).bots).find(
  2062. (value) => value.group?.threadId === "omt_selection",
  2063. )!;
  2064. expect(taskService.getTaskModelSelection).toHaveBeenCalledWith({ taskId: parent.activeTaskId });
  2065. const creation = vi.mocked(taskService.createTask).mock.calls.at(-1)?.[0];
  2066. expect(creation?.modelSelection ?? topic.draftOptions?.modelSelection).toEqual({
  2067. providerId: "glm",
  2068. modelId: "default",
  2069. options: { reasoningLevel: "max" },
  2070. });
  2071. });
  2072. it("inherits the group's explicit draft selection before any parent task exists", async () => {
  2073. const { send, repo } = setup();
  2074. await send("/enable");
  2075. const state = await repo.readState();
  2076. const parent = Object.values(state.bots).find((value) => value.group)!;
  2077. parent.draftOptions = {
  2078. provider: "glm",
  2079. modelSelection: {
  2080. providerId: "glm",
  2081. modelId: "default",
  2082. options: { reasoningLevel: "high" },
  2083. },
  2084. };
  2085. await repo.writeState(state);
  2086. await send("/status", "oc_a", "ou_user", "omt_draft");
  2087. const topic = Object.values((await repo.readState()).bots).find(
  2088. (value) => value.group?.threadId === "omt_draft",
  2089. )!;
  2090. expect(topic.draftOptions?.modelSelection).toEqual(parent.draftOptions.modelSelection);
  2091. });
  2092. it("inherits the current model selection when enabling a group", async () => {
  2093. const { send, repo, service } = setup();
  2094. const config = await repo.readConfig();
  2095. const modelSelection = {
  2096. providerId: "glm",
  2097. modelId: "default",
  2098. options: { reasoningLevel: "high" },
  2099. };
  2100. config.bots[0]!.currentOptions = { modelSelection, mode: "yolo" };
  2101. await repo.writeConfig(config);
  2102. await send("/enable");
  2103. const group = (await service.getBotStates()).find((state) => state.group)?.group;
  2104. expect(group?.currentOptions).toEqual({ modelSelection, mode: "default" });
  2105. });
  2106. it("does not inherit private sandbox and approval overrides", async () => {
  2107. const { send, repo, service } = setup();
  2108. const config = await repo.readConfig();
  2109. config.bots[0]!.currentOptions = {
  2110. mode: "yolo",
  2111. sandboxMode: "danger-full-access",
  2112. approvalPolicy: "never",
  2113. };
  2114. await repo.writeConfig(config);
  2115. await send("/enable");
  2116. const group = (await service.getBotStates()).find((s) => s.group)?.group;
  2117. expect(group?.currentOptions).toEqual({ mode: "default" });
  2118. });
  2119. it.each([
  2120. ["running", "运行"],
  2121. ["queued", "排队"],
  2122. ["interaction", "回答或审批"],
  2123. ] as const)("reports the CLI blocking reason %s", async (reason, expected) => {
  2124. const { send, taskService, service } = setup();
  2125. taskService.getBotGroupTaskBlockReason = vi.fn(async () => reason);
  2126. await send("/enable");
  2127. await send("work", "oc_a", "member");
  2128. const taskId = (await service.getBotStates()).find((value) => value.group)?.activeTaskId;
  2129. expect((await send("/new"))[0]?.text).toContain(expected);
  2130. expect((await service.getBotStates()).find((value) => value.group)?.activeTaskId).toBe(taskId);
  2131. });
  2132. it("opens a new draft after stop despite stale Bot permission options", async () => {
  2133. const { send, repo, service, taskService } = setup();
  2134. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  2135. await send("/enable");
  2136. await send("work", "oc_a", "member");
  2137. const state = await repo.readState();
  2138. const context = Object.values(state.bots).find((value) => value.group)!;
  2139. context.pendingPermissionOptions = [
  2140. {
  2141. requestId: "stopped-permission",
  2142. optionId: "allow_once",
  2143. command: "approve",
  2144. label: "Allow",
  2145. response: { decision: "allow", reason: "Approved once" },
  2146. },
  2147. ];
  2148. await repo.writeState(state);
  2149. vi.mocked(taskService.getBotGroupTaskBlockReason).mockClear();
  2150. await send("/new");
  2151. expect(taskService.getBotGroupTaskBlockReason).toHaveBeenCalledOnce();
  2152. const updated = (await service.getBotStates()).find((value) => value.group)!;
  2153. expect(updated.activeTaskId).toBeNull();
  2154. expect(updated.pendingPermissionOptions ?? []).toHaveLength(0);
  2155. });
  2156. it("allows only the queued input author or owner to cancel through CLI", async () => {
  2157. const { send, taskService } = setup();
  2158. taskService.cancelBotGroupInput = vi.fn(async (params) => ({
  2159. commandId: params.commandId,
  2160. status: "accepted",
  2161. revisionAtDecision: 2,
  2162. }));
  2163. await send("/enable");
  2164. const queued = await send("work", "oc_a", "member");
  2165. const cancel = queued[0]?.selection?.options[0]?.id;
  2166. expect(cancel).toMatch(/^\/queue-cancel /);
  2167. await send(cancel!, "oc_a", "other");
  2168. expect(taskService.cancelBotGroupInput).not.toHaveBeenCalled();
  2169. await send(cancel!, "oc_a", "member");
  2170. expect(taskService.cancelBotGroupInput).toHaveBeenCalledOnce();
  2171. });
  2172. it.each(["member", "ou_user"])(
  2173. "rejects legacy topic queue cancellation even from %s",
  2174. async (actorId) => {
  2175. const { send, service, repo, taskService } = setup(true);
  2176. taskService.cancelBotGroupInput = vi.fn();
  2177. await send("/enable");
  2178. await send("request A", "oc_a", "member", "omt_a");
  2179. const before = await repo.readState();
  2180. const context = before.bots[JSON.stringify(["feishu-1", "oc_a", "omt_a"])]!;
  2181. const commandId = Object.keys(context.group!.inputs!)[0]!;
  2182. const response = await service.handleInboundMessage({
  2183. botId: "feishu-1",
  2184. text: `/queue-cancel ${commandId}`,
  2185. groupCard: {
  2186. chatId: "oc_a",
  2187. threadId: "omt_a",
  2188. taskId: context.activeTaskId,
  2189. authorizationId: context.group!.authorizationId,
  2190. },
  2191. actor: {
  2192. botId: "feishu-1",
  2193. provider: "feishu",
  2194. chatType: "group",
  2195. chatId: "oc_a",
  2196. threadId: "omt_a",
  2197. rootMessageId: "root_omt_a",
  2198. providerUserId: actorId,
  2199. },
  2200. });
  2201. expect(taskService.cancelBotGroupInput).not.toHaveBeenCalled();
  2202. expect(response[0]?.callbackToastOnly).toBe(true);
  2203. expect(
  2204. (await repo.readState()).bots[JSON.stringify(["feishu-1", "oc_a", "omt_a"])]!.group!.inputs,
  2205. ).toEqual(context.group!.inputs);
  2206. },
  2207. );
  2208. it("admits queue cancellation while another input is waiting for CLI acknowledgement", async () => {
  2209. const { send, taskService } = setup();
  2210. taskService.cancelBotGroupInput = vi.fn(async (params) => ({
  2211. commandId: params.commandId,
  2212. status: "accepted",
  2213. revisionAtDecision: 2,
  2214. }));
  2215. await send("/enable");
  2216. const first = await send("first", "oc_a", "member");
  2217. let release!: () => void;
  2218. taskService.submitBotGroupInput = vi.fn(async (params) => {
  2219. await new Promise<void>((resolve) => {
  2220. release = resolve;
  2221. });
  2222. return {
  2223. commandId: params.commandId,
  2224. status: "accepted",
  2225. revisionAtDecision: 2,
  2226. result: { type: "inputAccepted", inputId: params.commandId, delivery: "queue" },
  2227. };
  2228. });
  2229. const pending = send("second", "oc_a", "member");
  2230. await vi.waitFor(() => expect(taskService.submitBotGroupInput).toHaveBeenCalled());
  2231. try {
  2232. await send(first[0]!.selection!.options[0]!.id, "oc_a", "member");
  2233. expect(taskService.cancelBotGroupInput).toHaveBeenCalledOnce();
  2234. } finally {
  2235. release();
  2236. await pending;
  2237. }
  2238. }, 2500);
  2239. it("keeps a group's task selection when the private conversation opens a draft", async () => {
  2240. const { send, service, taskService } = setup();
  2241. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  2242. await send("/enable");
  2243. await send("work", "oc_a", "member");
  2244. const created = await taskService.createTask.mock.results[0]!.value;
  2245. taskService.listTasks = vi.fn(async () => [created]);
  2246. await send("/new");
  2247. const menu = await send("/task");
  2248. expect(menu[0]?.selection?.options.length).toBeGreaterThan(0);
  2249. await service.handleInboundMessage({
  2250. botId: "feishu-1",
  2251. actor: {
  2252. botId: "feishu-1",
  2253. provider: "feishu",
  2254. providerUserId: "ou_user",
  2255. chatType: "private",
  2256. },
  2257. text: "/new",
  2258. });
  2259. // 任务仍归该项目;私人草稿不改变群内的项目候选。
  2260. await send("/task 1");
  2261. expect((await service.getBotStates()).find((value) => value.group)?.activeTaskId).toBe(
  2262. "task-1",
  2263. );
  2264. });
  2265. it("preserves historical identity but does not offer tasks outside the current project execution scope", async () => {
  2266. const { send, service, taskService, repo } = setup();
  2267. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  2268. await send("/enable");
  2269. await send("history", "oc_a", "member");
  2270. let state = await repo.readState();
  2271. const context = Object.values(state.bots).find((value) => value.group)!;
  2272. const originalPath = context.workspacePath;
  2273. expect(context.group?.taskWorkspaces?.[context.activeTaskId!]).toMatchObject({
  2274. workspacePath: originalPath,
  2275. });
  2276. const originalTaskId = context.activeTaskId!;
  2277. context.workspacePath = "/another-group-workspace";
  2278. context.workspaceIdentity = undefined;
  2279. context.workspaceId = context.workspacePath;
  2280. context.activeTaskId = null;
  2281. context.mode = "draft";
  2282. await repo.writeState(state);
  2283. taskService.listTasks = vi.fn(async (params) =>
  2284. params.workspacePath === originalPath
  2285. ? [
  2286. {
  2287. taskId: originalTaskId,
  2288. title: "Historical group task",
  2289. workspacePath: originalPath,
  2290. provider: "glm",
  2291. },
  2292. ]
  2293. : [],
  2294. );
  2295. const menu = await send("/task");
  2296. expect(menu[0]?.selection?.options ?? []).toEqual([]);
  2297. const retained = Object.values((await repo.readState()).bots).find((value) => value.group)!;
  2298. expect(retained.group?.taskWorkspaces?.[originalTaskId]).toMatchObject({
  2299. workspacePath: originalPath,
  2300. });
  2301. expect((await service.getBotStates()).find((value) => value.group)?.activeTaskId).toBeNull();
  2302. });
  2303. it("invalidates group cards across disable and re-enable", async () => {
  2304. const { send, service } = setup();
  2305. await send("/enable");
  2306. const previous = (await service.getBotStates()).find((s) => s.group)!;
  2307. await send("/disable");
  2308. await send("/enable");
  2309. const reply = await service.handleInboundMessage({
  2310. botId: "feishu-1",
  2311. text: "/status",
  2312. actor: {
  2313. botId: "feishu-1",
  2314. provider: "feishu",
  2315. chatType: "group",
  2316. chatId: "oc_a",
  2317. providerUserId: "ou_user",
  2318. },
  2319. groupCard: {
  2320. chatId: "oc_a",
  2321. taskId: previous.activeTaskId,
  2322. authorizationId: previous.group!.authorizationId!,
  2323. },
  2324. });
  2325. expect(reply[0]?.callbackToastOnly).toBe(true);
  2326. expect(reply[0]?.text).toContain("过期");
  2327. });
  2328. it("requires fresh group authorization after owner replacement, including changing back", async () => {
  2329. const { send, service } = setup();
  2330. await send("/enable");
  2331. const config = structuredClone(await service.getConfig());
  2332. config.bots[0]!.providerUserId = "new-owner";
  2333. await service.saveConfig(config);
  2334. config.bots[0]!.providerUserId = "ou_user";
  2335. await service.saveConfig(config);
  2336. expect((await service.getBotStates()).find((s) => s.group)?.group?.enabled).toBe(false);
  2337. expect((await send("hello", "oc_a", "member"))[0]?.text).toContain("启用");
  2338. });
  2339. it("lets a replacement owner explicitly authorize a fresh group context", async () => {
  2340. const { send, service } = setup();
  2341. await send("/enable");
  2342. const previous = (await service.getBotStates()).find((s) => s.group)!;
  2343. const config = structuredClone(await service.getConfig());
  2344. config.bots[0]!.providerUserId = "new-owner";
  2345. await service.saveConfig(config);
  2346. await send("/enable", "oc_a", "new-owner");
  2347. const current = (await service.getBotStates()).find((s) => s.group)!;
  2348. expect(current.group?.ownerId).toBe("new-owner");
  2349. expect(current.group?.enabled).toBe(true);
  2350. expect(current.group?.authorizationId).not.toBe(previous.group?.authorizationId);
  2351. expect(current.activeTaskId).toBeNull();
  2352. expect(current.group?.taskIds).toEqual([]);
  2353. });
  2354. it("cancels pending topic material when the bot is removed from the group", async () => {
  2355. const { send, service, taskService } = setup();
  2356. await send("/enable");
  2357. let release!: () => void;
  2358. historyMock.mockImplementationOnce(async (_bot, request) => {
  2359. await new Promise<void>((resolve) => {
  2360. release = resolve;
  2361. });
  2362. return { messages: [], checkpoint: request.messageId, hasGap: false };
  2363. });
  2364. const pending = send("removed material", "oc_a", "ou_user", "omt_removed");
  2365. await vi.waitFor(() => expect(release).toBeTypeOf("function"));
  2366. const response = await service.handleProviderCallbackResponse("feishu", {
  2367. botId: "feishu-1",
  2368. zcodeBotRemoved: true,
  2369. event: { chat_id: "oc_a" },
  2370. });
  2371. expect(response.ok).toBe(true);
  2372. release();
  2373. expect(await pending).toEqual([]);
  2374. await new Promise((resolve) => setTimeout(resolve, 0));
  2375. expect(taskService.createTask).not.toHaveBeenCalled();
  2376. expect(taskService.submitBotGroupInput).not.toHaveBeenCalled();
  2377. });
  2378. it("rejects an unverified bot removal event before revoking a group", async () => {
  2379. const { send, service, repo } = setup();
  2380. await send("/enable");
  2381. const config = await repo.readConfig();
  2382. config.bots[0]!.webhookSecretRef = "verification-secret";
  2383. await repo.writeConfig(config);
  2384. // 测试凭据服务对未登记的引用返回 null;下面使用实际登记凭据的独立服务。
  2385. const secured = f.createBotsService({
  2386. zcodeTaskService: f.createLegacyTaskService(),
  2387. repo: repo as never,
  2388. credentialService: f.createCredentialService({ "verification-secret": "expected-token" }),
  2389. runStartupBackgroundTasks: false,
  2390. });
  2391. services.push(secured);
  2392. const response = await secured.handleProviderCallbackResponse("feishu", {
  2393. botId: "feishu-1",
  2394. zcodeBotRemoved: true,
  2395. token: "incorrect-token",
  2396. event: { chat_id: "oc_a" },
  2397. });
  2398. expect(response.ok).toBe(false);
  2399. expect((await service.getBotStates()).find((s) => s.group)?.group?.enabled).toBe(true);
  2400. });
  2401. it("stops group synchronization on disable and restores only future events on enable", async () => {
  2402. const { send, taskService } = setup();
  2403. const dispose = vi.fn();
  2404. const ready = vi.fn(async () => null);
  2405. taskService.getBotGroupTaskBlockReason = ready;
  2406. const subscribe = vi.fn(() => () => ({ dispose }));
  2407. taskService.onDynamicTaskEvent = subscribe as never;
  2408. await send("/enable");
  2409. await send("E2E_GROUP_RESTORE", "oc_a", "member");
  2410. expect(subscribe).toHaveBeenCalledOnce();
  2411. await send("/disable");
  2412. expect(dispose).toHaveBeenCalledOnce();
  2413. await send("/enable");
  2414. expect(subscribe).toHaveBeenCalledTimes(2);
  2415. expect(ready).toHaveBeenCalled();
  2416. expect(ready.mock.invocationCallOrder.at(-1)).toBeLessThan(
  2417. subscribe.mock.invocationCallOrder.at(-1)!,
  2418. );
  2419. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  2420. expect(taskService.resumeTask).not.toHaveBeenCalled();
  2421. });
  2422. it("does not replay a persisted old message into the next group draft", async () => {
  2423. const { send, taskService } = setup();
  2424. taskService.getBotGroupTaskBlockReason = vi.fn(async () => null);
  2425. await send("/enable");
  2426. await send("persisted-message", "oc_a", "member");
  2427. await send("/new");
  2428. await send("persisted-message", "oc_a", "member");
  2429. expect(taskService.createTask).toHaveBeenCalledOnce();
  2430. expect(taskService.submitBotGroupInput).toHaveBeenCalledOnce();
  2431. });
  2432. it("persists the default group title after first admission", async () => {
  2433. const { send, taskService } = setup();
  2434. taskService.renameTask = vi.fn(async () => ({ taskId: "task-1" }) as never);
  2435. await send("/enable");
  2436. await send("first-title", "oc_a", "member");
  2437. expect(taskService.renameTask).toHaveBeenCalledWith(
  2438. expect.objectContaining({ taskId: "task-1", title: "飞书 · 测试群" }),
  2439. );
  2440. });
  2441. it("rejects an automation target that only has a legacy default-task alias", async () => {
  2442. const { send, service, taskService, repo } = setup();
  2443. await send("/enable");
  2444. const state = await repo.readState();
  2445. state.bots[JSON.stringify(["feishu-1", "oc_a"])].group!.topicAliases = {
  2446. omt_reply: { taskId: "original-task", rootMessageId: "om_reply" },
  2447. };
  2448. await repo.writeState(state);
  2449. taskService.onDynamicTaskEvent = vi.fn(() => () => ({ dispose() {} })) as never;
  2450. await service.watchAutomationRun({
  2451. workspacePath: "/tmp/workspace",
  2452. taskId: "scheduled-task",
  2453. target: {
  2454. provider: "feishu",
  2455. botId: "feishu-1",
  2456. providerUserId: "oc_a",
  2457. chatType: "group",
  2458. threadId: "omt_reply",
  2459. rootMessageId: "om_reply",
  2460. },
  2461. });
  2462. expect(taskService.onDynamicTaskEvent).not.toHaveBeenCalled();
  2463. });
  2464. it("does not attach a topic automation after its group is disabled", async () => {
  2465. const { send, service, taskService } = setup();
  2466. taskService.onDynamicTaskEvent = vi.fn(() => () => ({ dispose() {} })) as never;
  2467. await send("/enable");
  2468. await send("/status", "oc_a", "ou_user", "omt_a");
  2469. await send("/disable");
  2470. await service.watchAutomationRun({
  2471. workspacePath: "/tmp/workspace",
  2472. taskId: "scheduled-task",
  2473. target: {
  2474. provider: "feishu",
  2475. botId: "feishu-1",
  2476. providerUserId: "oc_a",
  2477. chatType: "group",
  2478. threadId: "omt_a",
  2479. rootMessageId: "root_omt_a",
  2480. },
  2481. });
  2482. expect(taskService.onDynamicTaskEvent).not.toHaveBeenCalled();
  2483. });
  2484. it("does not attach an automation delivery watcher to a disabled group", async () => {
  2485. const { send, service, taskService } = setup();
  2486. taskService.onDynamicTaskEvent = vi.fn(() => () => ({ dispose() {} })) as never;
  2487. await send("/enable");
  2488. await send("/disable");
  2489. await service.watchAutomationRun({
  2490. workspacePath: "/tmp/workspace",
  2491. taskId: "scheduled-task",
  2492. target: { provider: "feishu", botId: "feishu-1", providerUserId: "oc_a", chatType: "group" },
  2493. });
  2494. expect(taskService.onDynamicTaskEvent).not.toHaveBeenCalled();
  2495. });
  2496. });