botsService.fixtures.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /* eslint-disable max-lines -- Bot service 的共享测试桩集中维护协议、任务和模型 registry 能力。 */
  2. import { afterEach, vi } from "vitest";
  3. import type {
  4. ZCodeConfigOption,
  5. BotsConfigFile,
  6. BotsStateFile,
  7. Locale,
  8. ModelSelection,
  9. ZCodeTaskMode,
  10. ZCodeSessionSettingsState,
  11. } from "@zcode/shared";
  12. import {
  13. ZCODE_MODEL_REASONING_SEPARATOR,
  14. ZCODE_PROTOCOL_NAME,
  15. ZCODE_PROTOCOL_VERSION,
  16. botsConfigFileSchema,
  17. } from "@zcode/shared";
  18. export { botsConfigFileSchema };
  19. import type { IZCodeSessionService } from "../src/zcode-session/zcodeSession.js";
  20. import type { IZCodeTaskService } from "../src/session/zcodeTaskService.js";
  21. import type { IBroadcastService } from "../src/broadcast/broadcast.js";
  22. import type { ICredentialService } from "../src/credential/credential.js";
  23. import type { ISettingService } from "../src/setting/setting.js";
  24. import { createBotsService as createBotsServiceImpl } from "../src/bots/botsService.js";
  25. afterEach(() => {
  26. vi.unstubAllGlobals();
  27. });
  28. export const defaultUserCommands = {
  29. status: true,
  30. new: true,
  31. workspace: true,
  32. model: true,
  33. thoughtLevel: true,
  34. sandboxMode: true,
  35. approvalPolicy: true,
  36. reply: true,
  37. };
  38. export function createMemoryRepo(config: BotsConfigFile, state?: BotsStateFile) {
  39. let currentConfig = config;
  40. let currentState = state ?? { version: 3 as const, bots: {} };
  41. return {
  42. async readConfig() {
  43. return currentConfig;
  44. },
  45. async writeConfig(nextConfig: BotsConfigFile) {
  46. currentConfig = nextConfig;
  47. return currentConfig;
  48. },
  49. async readState() {
  50. return currentState;
  51. },
  52. async writeState(nextState: BotsStateFile) {
  53. currentState = nextState;
  54. return currentState;
  55. },
  56. };
  57. }
  58. export function createLegacyTaskService(): IZCodeTaskService {
  59. return {
  60. listTasks: vi.fn(async () => []),
  61. listDeletedTaskIds: vi.fn(async () => []),
  62. createTask: vi.fn(async () => ({
  63. taskId: "task-1",
  64. title: "Task 1",
  65. workspacePath: "/tmp/workspace",
  66. workspaceIdentity: "ssh://host/tmp/workspace",
  67. provider: "glm",
  68. })),
  69. sendPrompt: vi.fn(async () => undefined),
  70. setMode: vi.fn(async () => undefined),
  71. setConfigOption: vi.fn(async () => []),
  72. setModel: vi.fn(async () => []),
  73. getTaskConfigOptions: vi.fn(async () => []),
  74. getTaskModelSelection: vi.fn(async () => ({
  75. providerId: "glm",
  76. modelId: "glm-4.6",
  77. options: { reasoningLevel: "high" },
  78. })),
  79. getTaskSnapshot: vi.fn(async () => null),
  80. getTaskTokenUsage: vi.fn(async (params: { taskId: string }) => ({
  81. sessionId: params.taskId,
  82. totalTokens: 0,
  83. inputTokens: 0,
  84. outputTokens: 0,
  85. reasoningTokens: 0,
  86. cacheCreationTokens: 0,
  87. cacheReadTokens: 0,
  88. modelRequestCount: 0,
  89. modelErrorCount: 0,
  90. inputBaselineBySource: {},
  91. })),
  92. resumeTask: vi.fn(async () => ({
  93. taskId: "task-1",
  94. title: "Task 1",
  95. workspacePath: "/tmp/workspace",
  96. workspaceIdentity: "ssh://host/tmp/workspace",
  97. provider: "glm",
  98. })),
  99. switchAgent: vi.fn(async () => ({
  100. meta: {
  101. taskId: "task-1",
  102. title: "Task 1",
  103. workspacePath: "/tmp/workspace",
  104. workspaceIdentity: "ssh://host/tmp/workspace",
  105. provider: "glm",
  106. },
  107. provider: "glm",
  108. sessionId: "session-1",
  109. reusedBinding: false,
  110. })),
  111. respondPermission: vi.fn(async () => true),
  112. respondElicitation: vi.fn(async () => true),
  113. stopGeneration: vi.fn(async () => undefined),
  114. onDynamicStreamEvent: vi.fn(() => () => ({ dispose() {} })),
  115. } as unknown as IZCodeTaskService;
  116. }
  117. export function createCredentialService(values: Record<string, string> = {}): ICredentialService {
  118. return {
  119. load: vi.fn(async (key: string) => values[key] ?? null),
  120. save: vi.fn(async (key: string, value: string) => {
  121. values[key] = value;
  122. }),
  123. delete: vi.fn(async (key: string) => {
  124. delete values[key];
  125. }),
  126. };
  127. }
  128. export function createBroadcastService(): IBroadcastService {
  129. return {
  130. send: vi.fn(async () => undefined),
  131. onMessage: vi.fn(),
  132. } as unknown as IBroadcastService;
  133. }
  134. export function createSettingService(settings: {
  135. recentProjects?: string[];
  136. lastWorkspaceSession?: Array<
  137. | { kind: "local"; workspacePath: string }
  138. | (Record<string, unknown> & {
  139. kind: "remote";
  140. workspacePath: string;
  141. workspaceIdentity?: string;
  142. })
  143. >;
  144. locale?: Locale;
  145. enabledBuiltinAgentCliProviders?: Array<"claude" | "opencode" | "gemini" | "codex" | "glm">;
  146. }): ISettingService {
  147. return {
  148. get: vi.fn(async () => ({
  149. recentProjects: settings.recentProjects ?? [],
  150. lastWorkspaceSession: settings.lastWorkspaceSession ?? [],
  151. locale: settings.locale ?? "en-US",
  152. enabledBuiltinAgentCliProviders: settings.enabledBuiltinAgentCliProviders ?? ["glm"],
  153. })),
  154. update: vi.fn(async () => undefined),
  155. updateDataBaseDir: vi.fn(async () => undefined),
  156. ensureDefaultProject: vi.fn(async (path: string) => ({ path, created: false })),
  157. } as unknown as ISettingService;
  158. }
  159. export function createModelSelectionService(providers: readonly TestModelSelectionProvider[] = []) {
  160. return {
  161. getView: vi.fn(async (input?: { selection: ModelSelection | null }) => ({
  162. revision: 1,
  163. // 服务桩显式支持按输入返回结果;账号转换/失效分支由各自用例注入权威结果。
  164. ...(input ? { effectiveSelection: input.selection } : {}),
  165. providers: providers.map((provider) => ({
  166. providerId: provider.id,
  167. // 名称是 View 元数据;放进旧 config.label 会让展示测试错误回落到 ID。
  168. providerName: provider.name,
  169. config: {},
  170. models: provider.models.map((model) => ({
  171. modelId: typeof model === "string" ? model : model.id,
  172. config: typeof model === "string" ? {} : (model.config ?? {}),
  173. })),
  174. })),
  175. preferredSelection: providers[0]?.models[0]
  176. ? {
  177. providerId: providers[0].id,
  178. modelId:
  179. typeof providers[0].models[0] === "string"
  180. ? providers[0].models[0]
  181. : providers[0].models[0].id,
  182. }
  183. : undefined,
  184. })),
  185. };
  186. }
  187. export interface TestModelSelectionProvider {
  188. id: string;
  189. models: readonly (string | { id: string; config?: Record<string, unknown> })[];
  190. name: string;
  191. }
  192. function parseModelSelectionForTest(value: string): ModelSelection {
  193. const separatorIndex = value.indexOf("/");
  194. if (separatorIndex <= 0) {
  195. return { providerId: "glm", modelId: value || "default" };
  196. }
  197. const providerId = value.slice(0, separatorIndex);
  198. const rawModelId = value.slice(separatorIndex + 1);
  199. const reasoningSeparatorIndex = rawModelId.indexOf(ZCODE_MODEL_REASONING_SEPARATOR);
  200. if (reasoningSeparatorIndex <= 0 || reasoningSeparatorIndex >= rawModelId.length - 1) {
  201. return { providerId, modelId: rawModelId };
  202. }
  203. return {
  204. providerId,
  205. modelId: rawModelId.slice(0, reasoningSeparatorIndex),
  206. variant: rawModelId.slice(reasoningSeparatorIndex + 1),
  207. };
  208. }
  209. function normalizeZCodeModeForTest(value: unknown): ZCodeTaskMode {
  210. switch (value) {
  211. case "plan":
  212. case "build":
  213. case "yolo":
  214. case "auto":
  215. return value;
  216. case "read-only":
  217. return "plan";
  218. case "full-access":
  219. case "agent-full-access":
  220. return "yolo";
  221. default:
  222. return "build";
  223. }
  224. }
  225. function readSelectOption(
  226. configOptions: readonly ZCodeConfigOption[],
  227. category: string,
  228. ): (ZCodeConfigOption & { type: "select" }) | undefined {
  229. return configOptions.find(
  230. (option): option is ZCodeConfigOption & { type: "select" } =>
  231. option.type === "select" && (option.category === category || option.id === category),
  232. );
  233. }
  234. export function createZCodeSessionSettingsFromConfigOptions(
  235. configOptions: readonly ZCodeConfigOption[] = [],
  236. ): ZCodeSessionSettingsState {
  237. const modelOption = readSelectOption(configOptions, "model");
  238. const currentModelValue =
  239. typeof modelOption?.currentValue === "string"
  240. ? modelOption.currentValue
  241. : (modelOption?.options?.[0]?.value ?? "glm/default");
  242. const currentModel = parseModelSelectionForTest(currentModelValue);
  243. const modelOptions = modelOption?.options?.length
  244. ? modelOption.options
  245. : [{ value: currentModelValue, name: currentModel.modelId }];
  246. const thoughtOption = readSelectOption(configOptions, "thought_level");
  247. const modeOption = readSelectOption(configOptions, "mode");
  248. return {
  249. model: {
  250. current: currentModel,
  251. available: modelOptions.map((option) => ({
  252. ref: parseModelSelectionForTest(option.value),
  253. label: option.name ?? option.value,
  254. description: option.description,
  255. })),
  256. lastUsed: currentModel,
  257. },
  258. thoughtLevel: {
  259. enabled: Boolean(thoughtOption),
  260. current:
  261. typeof thoughtOption?.currentValue === "string"
  262. ? thoughtOption.currentValue
  263. : thoughtOption?.options?.[0]?.value,
  264. available:
  265. thoughtOption?.options?.map((option) => ({
  266. value: option.value,
  267. label: option.name ?? option.value,
  268. description: option.description,
  269. })) ?? [],
  270. },
  271. mode: {
  272. current: normalizeZCodeModeForTest(modeOption?.currentValue),
  273. },
  274. permission: {
  275. mode: normalizeZCodeModeForTest(modeOption?.currentValue),
  276. },
  277. };
  278. }
  279. function createZCodeWorkspaceState(
  280. settings: ZCodeSessionSettingsState = createZCodeSessionSettingsFromConfigOptions(),
  281. ): ZCodeWorkspaceStateSnapshot {
  282. return {
  283. workspace: {
  284. workspacePath: "/tmp/workspace",
  285. workspaceIdentity: "ssh://host/tmp/workspace",
  286. workspaceKey: "ssh://host/tmp/workspace",
  287. },
  288. settings,
  289. };
  290. }
  291. export function createZCodeSessionService(
  292. settings: ZCodeSessionSettingsState = createZCodeSessionSettingsFromConfigOptions(),
  293. ): IZCodeSessionService {
  294. const workspaceState = createZCodeWorkspaceState(settings);
  295. return {
  296. initializeWorkspace: vi.fn(async () => ({
  297. available: true,
  298. workspaceKey: workspaceState.workspace.workspaceKey,
  299. protocolName: ZCODE_PROTOCOL_NAME,
  300. protocolVersion: ZCODE_PROTOCOL_VERSION,
  301. transportKind: "stdio",
  302. })),
  303. readWorkspacePresentation: vi.fn(async () => ({
  304. workspace: workspaceState.workspace,
  305. mode: workspaceState.settings.mode.current,
  306. slashCommands: [],
  307. })),
  308. updateProviderRegistry: vi.fn(async () => ({
  309. applied: true,
  310. revision: "test-provider-registry",
  311. })),
  312. } as unknown as IZCodeSessionService;
  313. }
  314. export function createBotsService(
  315. deps: Omit<
  316. Parameters<typeof createBotsServiceImpl>[0],
  317. "zcodeSessionService" | "zcodeTaskService"
  318. > & {
  319. zcodeTaskService?: IZCodeTaskService;
  320. /** 旧测试名保留为别名;真实注入的是 ZCode task service。 */
  321. legacyTaskService?: IZCodeTaskService;
  322. zcodeSessionService?: IZCodeSessionService;
  323. },
  324. ): ReturnType<typeof createBotsServiceImpl> {
  325. const {
  326. legacyTaskService,
  327. zcodeTaskService: providedZCodeTaskService,
  328. zcodeSessionService: _providedZCodeSessionService,
  329. ...rest
  330. } = deps;
  331. const zcodeTaskService =
  332. providedZCodeTaskService ?? legacyTaskService ?? createLegacyTaskService();
  333. const modelSelectionService =
  334. deps.modelSelectionService ??
  335. createModelSelectionService([{ id: "glm", name: "GLM", models: ["default"] }]);
  336. return createBotsServiceImpl({
  337. // Bots 不再持久化 workspace 候选项;测试默认从 settings.lastWorkspaceSession 提供当前工作区。
  338. settingService: createSettingService({
  339. locale: "zh-CN",
  340. lastWorkspaceSession: [
  341. {
  342. kind: "remote",
  343. workspacePath: "/tmp/workspace",
  344. workspaceIdentity: "ssh://host/tmp/workspace",
  345. },
  346. ],
  347. }),
  348. remoteWorkspaceService: {
  349. isConnected: vi.fn(async () => true),
  350. ensureConnected: vi.fn(async () => ({ ok: true })),
  351. getZCodeTaskService: vi.fn(async () => zcodeTaskService),
  352. getModelSelectionService: vi.fn(async () => modelSelectionService),
  353. },
  354. modelSelectionService,
  355. ...rest,
  356. zcodeTaskService,
  357. });
  358. }
  359. export const baseConfig: BotsConfigFile = {
  360. version: 3,
  361. bots: [
  362. {
  363. id: "webhook-1",
  364. name: "Webhook",
  365. provider: "webhook",
  366. enabled: true,
  367. webhookSecretRef: "secret-1",
  368. allowedWorkspaces: ["*"],
  369. allowedCommands: defaultUserCommands,
  370. currentOptions: {},
  371. replyMode: "assistant_changes",
  372. },
  373. ],
  374. };
  375. export const telegramConfig: BotsConfigFile = {
  376. ...baseConfig,
  377. bots: [
  378. {
  379. ...baseConfig.bots[0]!,
  380. id: "telegram-1",
  381. name: "Telegram",
  382. provider: "telegram",
  383. credentialRef: "telegram-token",
  384. webhookSecretRef: undefined,
  385. providerUserId: "user-1",
  386. allowedWorkspaces: ["*"],
  387. },
  388. ],
  389. };
  390. export const feishuConfig: BotsConfigFile = {
  391. ...baseConfig,
  392. bots: [
  393. {
  394. ...baseConfig.bots[0]!,
  395. id: "feishu-1",
  396. name: "Feishu",
  397. provider: "feishu",
  398. credentialRef: "feishu-secret",
  399. webhookSecretRef: undefined,
  400. feishuAppId: "cli_xxx",
  401. providerUserId: "ou_user",
  402. allowedWorkspaces: ["*"],
  403. },
  404. ],
  405. };
  406. export const weixinConfig: BotsConfigFile = {
  407. ...baseConfig,
  408. bots: [
  409. {
  410. ...baseConfig.bots[0]!,
  411. id: "weixin-1",
  412. name: "Weixin",
  413. provider: "weixin",
  414. credentialRef: "weixin-token",
  415. webhookSecretRef: undefined,
  416. allowedWorkspaces: ["*"],
  417. },
  418. ],
  419. };