botsService.config.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import { describe, expect, it, vi } from "vitest";
  2. import * as f from "./botsService.fixtures.js";
  3. const actor = {
  4. provider: "webhook" as const,
  5. botId: "webhook-1",
  6. providerUserId: "user-1",
  7. chatType: "private" as const,
  8. };
  9. function createTestProvider(params: {
  10. id: string;
  11. name: string;
  12. models: string[];
  13. }): f.TestModelSelectionProvider {
  14. return {
  15. id: params.id,
  16. name: params.name,
  17. models: params.models,
  18. };
  19. }
  20. describe("botsService config", () => {
  21. it("Bot 主动选模型保存目标最高档位,不继承旧模型的 low", async () => {
  22. const repo = f.createMemoryRepo(
  23. {
  24. ...f.baseConfig,
  25. bots: [
  26. {
  27. ...f.baseConfig.bots[0]!,
  28. providerUserId: "user-1",
  29. },
  30. ],
  31. },
  32. {
  33. version: 3,
  34. bots: {
  35. "webhook-1": {
  36. botId: "webhook-1",
  37. workspacePath: "/tmp/workspace",
  38. mode: "draft",
  39. activeTaskId: null,
  40. updatedAt: 1,
  41. draftOptions: {
  42. provider: "zcode",
  43. modelSelection: {
  44. providerId: "target",
  45. modelId: "old",
  46. options: { reasoningLevel: "low" },
  47. },
  48. },
  49. },
  50. },
  51. },
  52. );
  53. const service = f.createBotsService({
  54. repo: repo as never,
  55. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  56. modelSelectionService: f.createModelSelectionService([
  57. {
  58. id: "target",
  59. name: "Target",
  60. models: [
  61. {
  62. id: "new",
  63. config: { optionSpecs: { reasoningLevel: { values: ["low", "high", "max"] } } },
  64. },
  65. ],
  66. },
  67. ]),
  68. });
  69. try {
  70. await service.handleInboundMessage({
  71. botId: "webhook-1",
  72. text: "/model custom:target:new",
  73. actor,
  74. });
  75. expect((await repo.readState()).bots["webhook-1"]?.draftOptions?.modelSelection).toEqual({
  76. providerId: "target",
  77. modelId: "new",
  78. options: { reasoningLevel: "max" },
  79. });
  80. } finally {
  81. service.disposeAll();
  82. }
  83. });
  84. it("accepts v3 bots config and rejects legacy bot config fields", () => {
  85. expect(f.botsConfigFileSchema.safeParse(f.baseConfig).success).toBe(true);
  86. // Bugfix: Bots v3 不做旧 channels.json 隐式迁移;schema 必须 strict,避免未知字段被 Zod strip。
  87. expect(f.botsConfigFileSchema.safeParse({ version: 1, channels: [] }).success).toBe(false);
  88. expect(f.botsConfigFileSchema.safeParse({ ...f.baseConfig, channels: [] }).success).toBe(false);
  89. });
  90. it("binds a private actor to the requested bot", async () => {
  91. const repo = f.createMemoryRepo(f.baseConfig);
  92. const service = f.createBotsService({
  93. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  94. legacyTaskService: f.createLegacyTaskService(),
  95. repo: repo as never,
  96. });
  97. const bind = await service.createBindCode({ botId: "webhook-1" });
  98. const replies = await service.handleInboundMessage({
  99. botId: "webhook-1",
  100. text: `/bind ${bind.code}`,
  101. actor,
  102. });
  103. expect(replies[0]?.text).toContain("绑定成功");
  104. expect((await repo.readConfig()).bots[0]).toMatchObject({
  105. id: "webhook-1",
  106. providerUserId: "user-1",
  107. allowedWorkspaces: ["*"],
  108. });
  109. service.disposeAll();
  110. });
  111. it("rejects duplicate enabled provider bindings", async () => {
  112. const repo = f.createMemoryRepo({
  113. ...f.baseConfig,
  114. bots: [
  115. {
  116. ...f.baseConfig.bots[0]!,
  117. providerUserId: "user-1",
  118. },
  119. {
  120. ...f.baseConfig.bots[0]!,
  121. id: "webhook-2",
  122. name: "Webhook 2",
  123. providerUserId: "user-1",
  124. },
  125. ],
  126. });
  127. const service = f.createBotsService({
  128. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  129. legacyTaskService: f.createLegacyTaskService(),
  130. repo: repo as never,
  131. });
  132. await expect(service.saveBot({ bot: (await repo.readConfig()).bots[1]! })).rejects.toThrow(
  133. /provider user/,
  134. );
  135. service.disposeAll();
  136. });
  137. it("normalizes empty allowedWorkspaces to wildcard", async () => {
  138. const repo = f.createMemoryRepo(f.baseConfig);
  139. const service = f.createBotsService({
  140. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  141. legacyTaskService: f.createLegacyTaskService(),
  142. repo: repo as never,
  143. });
  144. await service.saveBot({
  145. bot: {
  146. ...f.baseConfig.bots[0]!,
  147. allowedWorkspaces: [],
  148. },
  149. });
  150. expect((await repo.readConfig()).bots[0]?.allowedWorkspaces).toEqual(["*"]);
  151. service.disposeAll();
  152. });
  153. it("does not run remote-disabled bot background work after config changes", async () => {
  154. const repo = f.createMemoryRepo(f.baseConfig);
  155. const fetchImpl = vi.fn(
  156. async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
  157. );
  158. vi.stubGlobal("fetch", fetchImpl);
  159. const modelSelectionService = f.createModelSelectionService([
  160. createTestProvider({
  161. id: "new-provider",
  162. name: "DeepSeek",
  163. models: ["deepseek-v4-flash"],
  164. }),
  165. ]);
  166. const service = f.createBotsService({
  167. repo: repo as never,
  168. modelSelectionService,
  169. credentialService: f.createCredentialService({
  170. "secret-1": "secret",
  171. "telegram-token": "telegram-secret",
  172. }),
  173. runStartupBackgroundTasks: false,
  174. warmCandidateCachesOnStartup: false,
  175. });
  176. await service.saveConfig(f.telegramConfig);
  177. await new Promise((resolve) => setTimeout(resolve, 50));
  178. expect(modelSelectionService.getView).not.toHaveBeenCalled();
  179. expect(fetchImpl).not.toHaveBeenCalled();
  180. service.disposeAll();
  181. });
  182. it("allows an unnamed bot so UI can show a fallback display name", async () => {
  183. const repo = f.createMemoryRepo(f.baseConfig);
  184. const service = f.createBotsService({
  185. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  186. legacyTaskService: f.createLegacyTaskService(),
  187. repo: repo as never,
  188. });
  189. await service.saveBot({
  190. bot: {
  191. ...f.baseConfig.bots[0]!,
  192. name: " ",
  193. },
  194. });
  195. expect((await repo.readConfig()).bots[0]?.name).toBe("");
  196. service.disposeAll();
  197. });
  198. it("/model 展示当前候选,但不把已保存选择按同名模型换到其他供应商", async () => {
  199. const repo = f.createMemoryRepo(
  200. {
  201. ...f.baseConfig,
  202. bots: [
  203. {
  204. ...f.baseConfig.bots[0]!,
  205. providerUserId: "user-1",
  206. },
  207. ],
  208. },
  209. {
  210. version: 3,
  211. bots: {
  212. "webhook-1": {
  213. botId: "webhook-1",
  214. workspacePath: "/tmp/workspace",
  215. workspaceIdentity: "ssh://host/tmp/workspace",
  216. mode: "draft",
  217. activeTaskId: null,
  218. draftOptions: {
  219. provider: "glm",
  220. modelSelection: { providerId: "old-provider", modelId: "deepseek-v4-flash" },
  221. },
  222. updatedAt: 1,
  223. },
  224. },
  225. },
  226. );
  227. const currentProvider = createTestProvider({
  228. id: "new-provider",
  229. name: "DeepSeek",
  230. models: ["deepseek-v4-flash"],
  231. });
  232. const service = f.createBotsService({
  233. repo: repo as never,
  234. modelSelectionService: f.createModelSelectionService([currentProvider]),
  235. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  236. });
  237. const replies = await service.handleInboundMessage({
  238. botId: "webhook-1",
  239. text: "/model",
  240. actor,
  241. });
  242. expect(replies[0]?.selection?.options.some((option) => option.id === "new-provider")).toBe(
  243. true,
  244. );
  245. await expect(repo.readState()).resolves.toMatchObject({
  246. bots: {
  247. "webhook-1": {
  248. draftOptions: {
  249. modelSelection: {
  250. providerId: "old-provider",
  251. modelId: "deepseek-v4-flash",
  252. },
  253. },
  254. },
  255. },
  256. });
  257. service.disposeAll();
  258. });
  259. it("/model 标记当前生效的账号模型,但只读菜单不覆盖原草稿", async () => {
  260. const original = {
  261. providerId: "account:bigmodel-individual-coding-plan",
  262. modelId: "GLM-5.3",
  263. options: { reasoningLevel: "high" },
  264. };
  265. const effective = { ...original, providerId: "account:bigmodel-team-coding-plan" };
  266. const repo = f.createMemoryRepo(
  267. { ...f.baseConfig, bots: [{ ...f.baseConfig.bots[0]!, providerUserId: "user-1" }] },
  268. {
  269. version: 3,
  270. bots: {
  271. "webhook-1": {
  272. botId: "webhook-1",
  273. workspacePath: "/tmp/workspace",
  274. mode: "draft",
  275. activeTaskId: null,
  276. draftOptions: { provider: "glm", modelSelection: original },
  277. updatedAt: 1,
  278. },
  279. },
  280. },
  281. );
  282. const selectionService = f.createModelSelectionService([
  283. { id: effective.providerId, name: "Team", models: [effective.modelId] },
  284. ]);
  285. const view = await selectionService.getView();
  286. selectionService.getView.mockImplementation(async (input) => ({
  287. ...view,
  288. ...(input ? { effectiveSelection: effective } : {}),
  289. }));
  290. const service = f.createBotsService({
  291. repo: repo as never,
  292. modelSelectionService: selectionService,
  293. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  294. });
  295. try {
  296. const replies = await service.handleInboundMessage({
  297. botId: "webhook-1",
  298. text: "/model",
  299. actor,
  300. });
  301. expect(replies[0]?.selection?.currentId).toBe(effective.providerId);
  302. expect((await repo.readState()).bots["webhook-1"]?.draftOptions?.modelSelection).toEqual(
  303. original,
  304. );
  305. } finally {
  306. service.disposeAll();
  307. }
  308. });
  309. it("/model 每次打开都与当前 Model Selection View 对齐", async () => {
  310. const repo = f.createMemoryRepo({
  311. ...f.baseConfig,
  312. bots: [
  313. {
  314. ...f.baseConfig.bots[0]!,
  315. providerUserId: actor.providerUserId,
  316. },
  317. ],
  318. });
  319. const oldProvider = createTestProvider({
  320. id: "old-provider",
  321. name: "Old Provider",
  322. models: ["old-model"],
  323. });
  324. const newProvider = createTestProvider({
  325. id: "new-provider",
  326. name: "New Provider",
  327. models: ["new-model"],
  328. });
  329. let currentProviders = [oldProvider];
  330. const modelSelectionService = f.createModelSelectionService();
  331. vi.mocked(modelSelectionService.getView).mockImplementation(async () =>
  332. f.createModelSelectionService(currentProviders).getView(),
  333. );
  334. const service = f.createBotsService({
  335. repo: repo as never,
  336. modelSelectionService,
  337. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  338. });
  339. const firstReplies = await service.handleInboundMessage({
  340. botId: "webhook-1",
  341. text: "/model",
  342. actor,
  343. });
  344. expect(firstReplies[0]?.selection?.options.map((option) => option.id)).toContain(
  345. "old-provider",
  346. );
  347. currentProviders = [newProvider];
  348. const secondReplies = await service.handleInboundMessage({
  349. botId: "webhook-1",
  350. text: "/model",
  351. actor,
  352. });
  353. const secondProviderIds = secondReplies[0]?.selection?.options.map((option) => option.id);
  354. expect(secondProviderIds).toContain("new-provider");
  355. expect(secondProviderIds).not.toContain("old-provider");
  356. service.disposeAll();
  357. });
  358. it("同路径的远端读取失败不使用之前本地菜单缓存,恢复后显示目标模型", async () => {
  359. const repo = f.createMemoryRepo(
  360. {
  361. ...f.baseConfig,
  362. bots: [{ ...f.baseConfig.bots[0]!, providerUserId: actor.providerUserId }],
  363. },
  364. {
  365. version: 3,
  366. bots: {
  367. "webhook-1": {
  368. botId: "webhook-1",
  369. workspacePath: "/tmp/workspace",
  370. workspaceId: "/tmp/workspace",
  371. mode: "draft",
  372. activeTaskId: null,
  373. updatedAt: 1,
  374. draftOptions: {
  375. provider: "zcode",
  376. modelSelection: {
  377. providerId: "local-only",
  378. modelId: "m",
  379. options: { reasoningLevel: "high" },
  380. },
  381. },
  382. },
  383. },
  384. },
  385. );
  386. const local = f.createModelSelectionService([
  387. { id: "local-only", name: "Local Only", models: ["m"] },
  388. ]);
  389. const remote = f.createModelSelectionService([
  390. { id: "remote-only", name: "Remote Only", models: ["m"] },
  391. ]);
  392. const getRemote = vi.fn(async () => remote);
  393. const settingService = f.createSettingService({
  394. locale: "zh-CN",
  395. lastWorkspaceSession: [{ kind: "local", workspacePath: "/tmp/workspace" }],
  396. });
  397. const service = f.createBotsService({
  398. repo: repo as never,
  399. modelSelectionService: local,
  400. settingService,
  401. remoteWorkspaceService: {
  402. isConnected: vi.fn(async () => true),
  403. ensureConnected: vi.fn(async () => ({ ok: true })),
  404. getZCodeTaskService: vi.fn(async () => f.createLegacyTaskService()),
  405. getModelSelectionService: getRemote,
  406. },
  407. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  408. });
  409. const menu = () => service.handleInboundMessage({ botId: "webhook-1", text: "/model", actor });
  410. try {
  411. expect((await menu())[0]?.selection?.options.map((option) => option.id)).toContain(
  412. "local-only",
  413. );
  414. const state = await repo.readState();
  415. const contextKey = Object.keys(state.bots)[0]!;
  416. const original = state.bots[contextKey]!;
  417. vi.mocked(settingService.get).mockImplementation(
  418. f.createSettingService({
  419. locale: "zh-CN",
  420. lastWorkspaceSession: [
  421. {
  422. kind: "remote",
  423. workspacePath: "/tmp/workspace",
  424. workspaceIdentity: "ssh://other/tmp/workspace",
  425. },
  426. ],
  427. }).get,
  428. );
  429. await repo.writeState({
  430. ...state,
  431. bots: {
  432. ...state.bots,
  433. [contextKey]: {
  434. ...original,
  435. workspaceId: "ssh://other/tmp/workspace",
  436. workspaceIdentity: "ssh://other/tmp/workspace",
  437. },
  438. },
  439. });
  440. const before = structuredClone(await repo.readState());
  441. remote.getView.mockRejectedValue(new Error("remote offline"));
  442. const unavailable = await menu();
  443. expect(getRemote).toHaveBeenCalledWith({
  444. workspacePath: "/tmp/workspace",
  445. workspaceIdentity: "ssh://other/tmp/workspace",
  446. });
  447. expect(unavailable[0]?.text).toContain("未找到模型供应商");
  448. expect(unavailable[0]?.selection).toBeUndefined();
  449. expect((await repo.readState()).bots[contextKey]?.draftOptions).toEqual(
  450. before.bots[contextKey]?.draftOptions,
  451. );
  452. remote.getView.mockImplementation(
  453. f.createModelSelectionService([{ id: "remote-only", name: "Remote Only", models: ["m"] }])
  454. .getView,
  455. );
  456. const restored = (await menu())[0]?.selection?.options.map((option) => option.id);
  457. expect(restored).toContain("remote-only");
  458. expect(restored).not.toContain("local-only");
  459. expect(getRemote).toHaveBeenCalled();
  460. } finally {
  461. service.disposeAll();
  462. }
  463. });
  464. it("空 Model Selection View 不回退持久化的旧 Provider 菜单", async () => {
  465. const repo = f.createMemoryRepo({
  466. ...f.baseConfig,
  467. bots: [
  468. {
  469. ...f.baseConfig.bots[0]!,
  470. providerUserId: actor.providerUserId,
  471. },
  472. ],
  473. });
  474. const service = f.createBotsService({
  475. repo: repo as never,
  476. modelSelectionService: f.createModelSelectionService(),
  477. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  478. });
  479. const replies = await service.handleInboundMessage({
  480. botId: "webhook-1",
  481. text: "/model",
  482. actor,
  483. });
  484. expect(replies[0]?.text).toContain("未找到模型供应商");
  485. expect(replies[0]?.text).not.toContain("Cached Provider");
  486. service.disposeAll();
  487. });
  488. });