botsService.fixtures.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 type { VirtualProject } from "../src/project/contract.js";
  25. import { remoteHostIdFromWorkspaceIdentity } from "@zcode/shared";
  26. import { createBotsService as createBotsServiceImpl } from "../src/bots/botsService.js";
  27. afterEach(() => {
  28. vi.unstubAllGlobals();
  29. });
  30. export const defaultUserCommands = {
  31. status: true,
  32. new: true,
  33. workspace: true,
  34. model: true,
  35. thoughtLevel: true,
  36. sandboxMode: true,
  37. approvalPolicy: true,
  38. reply: true,
  39. };
  40. export function createMemoryRepo(config: BotsConfigFile, state?: BotsStateFile) {
  41. let currentConfig = config;
  42. let currentState = state ?? { version: 3 as const, bots: {} };
  43. return {
  44. async readConfig() {
  45. return currentConfig;
  46. },
  47. async writeConfig(nextConfig: BotsConfigFile) {
  48. currentConfig = nextConfig;
  49. return currentConfig;
  50. },
  51. async readState() {
  52. return currentState;
  53. },
  54. async writeState(nextState: BotsStateFile) {
  55. currentState = nextState;
  56. return currentState;
  57. },
  58. async updateContext(
  59. botId: string,
  60. update: (
  61. current: BotsStateFile["bots"][string] | undefined,
  62. ) => BotsStateFile["bots"][string] | undefined,
  63. ) {
  64. const next = update(currentState.bots[botId]);
  65. if (next) currentState.bots[botId] = next;
  66. else delete currentState.bots[botId];
  67. return next;
  68. },
  69. };
  70. }
  71. export function createLegacyTaskService(): IZCodeTaskService {
  72. return {
  73. listTasks: vi.fn(async () => []),
  74. listDeletedTaskIds: vi.fn(async () => []),
  75. createTask: vi.fn(async () => ({
  76. taskId: "task-1",
  77. title: "Task 1",
  78. workspacePath: "/tmp/workspace",
  79. workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
  80. provider: "glm",
  81. })),
  82. sendPrompt: vi.fn(async () => undefined),
  83. setMode: vi.fn(async () => undefined),
  84. setConfigOption: vi.fn(async () => []),
  85. setModel: vi.fn(async () => []),
  86. getTaskConfigOptions: vi.fn(async () => []),
  87. getTaskModelSelection: vi.fn(async () => ({
  88. providerId: "glm",
  89. modelId: "glm-4.6",
  90. options: { reasoningLevel: "high" },
  91. })),
  92. getTaskSnapshot: vi.fn(async () => null),
  93. getTaskTokenUsage: vi.fn(async (params: { taskId: string }) => ({
  94. sessionId: params.taskId,
  95. totalTokens: 0,
  96. inputTokens: 0,
  97. outputTokens: 0,
  98. reasoningTokens: 0,
  99. cacheCreationTokens: 0,
  100. cacheReadTokens: 0,
  101. modelRequestCount: 0,
  102. modelErrorCount: 0,
  103. inputBaselineBySource: {},
  104. })),
  105. resumeTask: vi.fn(async () => ({
  106. taskId: "task-1",
  107. title: "Task 1",
  108. workspacePath: "/tmp/workspace",
  109. workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
  110. provider: "glm",
  111. })),
  112. switchAgent: vi.fn(async () => ({
  113. meta: {
  114. taskId: "task-1",
  115. title: "Task 1",
  116. workspacePath: "/tmp/workspace",
  117. workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
  118. provider: "glm",
  119. },
  120. provider: "glm",
  121. sessionId: "session-1",
  122. reusedBinding: false,
  123. })),
  124. respondPermission: vi.fn(async () => true),
  125. respondElicitation: vi.fn(async () => true),
  126. stopGeneration: vi.fn(async () => undefined),
  127. onDynamicStreamEvent: vi.fn(() => () => ({ dispose() {} })),
  128. } as unknown as IZCodeTaskService;
  129. }
  130. export function createCredentialService(values: Record<string, string> = {}): ICredentialService {
  131. return {
  132. load: vi.fn(async (key: string) => values[key] ?? null),
  133. save: vi.fn(async (key: string, value: string) => {
  134. values[key] = value;
  135. }),
  136. delete: vi.fn(async (key: string) => {
  137. delete values[key];
  138. }),
  139. };
  140. }
  141. export function createBroadcastService(): IBroadcastService {
  142. return {
  143. send: vi.fn(async () => undefined),
  144. onMessage: vi.fn(),
  145. } as unknown as IBroadcastService;
  146. }
  147. export function createSettingService(settings: {
  148. recentProjects?: string[];
  149. lastWorkspaceSession?: Array<
  150. | { kind: "local"; workspacePath: string }
  151. | (Record<string, unknown> & {
  152. kind: "remote";
  153. workspacePath: string;
  154. workspaceIdentity?: string;
  155. })
  156. >;
  157. locale?: Locale;
  158. enabledBuiltinAgentCliProviders?: Array<"claude" | "opencode" | "gemini" | "codex" | "glm">;
  159. }): ISettingService {
  160. return {
  161. get: vi.fn(async () => ({
  162. recentProjects: settings.recentProjects ?? [],
  163. lastWorkspaceSession: settings.lastWorkspaceSession ?? [],
  164. locale: settings.locale ?? "en-US",
  165. enabledBuiltinAgentCliProviders: settings.enabledBuiltinAgentCliProviders ?? ["glm"],
  166. })),
  167. update: vi.fn(async () => undefined),
  168. updateDataBaseDir: vi.fn(async () => undefined),
  169. } as unknown as ISettingService;
  170. }
  171. export function createModelSelectionService(providers: readonly TestModelSelectionProvider[] = []) {
  172. return {
  173. getView: vi.fn(async (input?: { selection: ModelSelection | null }) => ({
  174. revision: 1,
  175. // 服务桩显式支持按输入返回结果;账号转换/失效分支由各自用例注入权威结果。
  176. ...(input ? { effectiveSelection: input.selection } : {}),
  177. providers: providers.map((provider) => ({
  178. providerId: provider.id,
  179. // 名称是 View 元数据;放进旧 config.label 会让展示测试错误回落到 ID。
  180. providerName: provider.name,
  181. config: {},
  182. models: provider.models.map((model) => ({
  183. modelId: typeof model === "string" ? model : model.id,
  184. config: typeof model === "string" ? {} : (model.config ?? {}),
  185. })),
  186. })),
  187. preferredSelection: providers[0]?.models[0]
  188. ? {
  189. providerId: providers[0].id,
  190. modelId:
  191. typeof providers[0].models[0] === "string"
  192. ? providers[0].models[0]
  193. : providers[0].models[0].id,
  194. }
  195. : undefined,
  196. })),
  197. };
  198. }
  199. export interface TestModelSelectionProvider {
  200. id: string;
  201. models: readonly (string | { id: string; config?: Record<string, unknown> })[];
  202. name: string;
  203. }
  204. function parseModelSelectionForTest(value: string): ModelSelection {
  205. const separatorIndex = value.indexOf("/");
  206. if (separatorIndex <= 0) {
  207. return { providerId: "glm", modelId: value || "default" };
  208. }
  209. const providerId = value.slice(0, separatorIndex);
  210. const rawModelId = value.slice(separatorIndex + 1);
  211. const reasoningSeparatorIndex = rawModelId.indexOf(ZCODE_MODEL_REASONING_SEPARATOR);
  212. if (reasoningSeparatorIndex <= 0 || reasoningSeparatorIndex >= rawModelId.length - 1) {
  213. return { providerId, modelId: rawModelId };
  214. }
  215. return {
  216. providerId,
  217. modelId: rawModelId.slice(0, reasoningSeparatorIndex),
  218. variant: rawModelId.slice(reasoningSeparatorIndex + 1),
  219. };
  220. }
  221. function normalizeZCodeModeForTest(value: unknown): ZCodeTaskMode {
  222. switch (value) {
  223. case "plan":
  224. case "build":
  225. case "yolo":
  226. case "auto":
  227. return value;
  228. case "read-only":
  229. return "plan";
  230. case "full-access":
  231. case "agent-full-access":
  232. return "yolo";
  233. default:
  234. return "build";
  235. }
  236. }
  237. function readSelectOption(
  238. configOptions: readonly ZCodeConfigOption[],
  239. category: string,
  240. ): (ZCodeConfigOption & { type: "select" }) | undefined {
  241. return configOptions.find(
  242. (option): option is ZCodeConfigOption & { type: "select" } =>
  243. option.type === "select" && (option.category === category || option.id === category),
  244. );
  245. }
  246. export function createZCodeSessionSettingsFromConfigOptions(
  247. configOptions: readonly ZCodeConfigOption[] = [],
  248. ): ZCodeSessionSettingsState {
  249. const modelOption = readSelectOption(configOptions, "model");
  250. const currentModelValue =
  251. typeof modelOption?.currentValue === "string"
  252. ? modelOption.currentValue
  253. : (modelOption?.options?.[0]?.value ?? "glm/default");
  254. const currentModel = parseModelSelectionForTest(currentModelValue);
  255. const modelOptions = modelOption?.options?.length
  256. ? modelOption.options
  257. : [{ value: currentModelValue, name: currentModel.modelId }];
  258. const thoughtOption = readSelectOption(configOptions, "thought_level");
  259. const modeOption = readSelectOption(configOptions, "mode");
  260. return {
  261. model: {
  262. current: currentModel,
  263. available: modelOptions.map((option) => ({
  264. ref: parseModelSelectionForTest(option.value),
  265. label: option.name ?? option.value,
  266. description: option.description,
  267. })),
  268. lastUsed: currentModel,
  269. },
  270. thoughtLevel: {
  271. enabled: Boolean(thoughtOption),
  272. current:
  273. typeof thoughtOption?.currentValue === "string"
  274. ? thoughtOption.currentValue
  275. : thoughtOption?.options?.[0]?.value,
  276. available:
  277. thoughtOption?.options?.map((option) => ({
  278. value: option.value,
  279. label: option.name ?? option.value,
  280. description: option.description,
  281. })) ?? [],
  282. },
  283. mode: {
  284. current: normalizeZCodeModeForTest(modeOption?.currentValue),
  285. },
  286. permission: {
  287. mode: normalizeZCodeModeForTest(modeOption?.currentValue),
  288. },
  289. };
  290. }
  291. function createZCodeWorkspaceState(
  292. settings: ZCodeSessionSettingsState = createZCodeSessionSettingsFromConfigOptions(),
  293. ): ZCodeWorkspaceStateSnapshot {
  294. return {
  295. workspace: {
  296. workspacePath: "/tmp/workspace",
  297. workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
  298. workspaceKey: "remote:server:test-owner:/tmp/workspace",
  299. },
  300. settings,
  301. };
  302. }
  303. export function createZCodeSessionService(
  304. settings: ZCodeSessionSettingsState = createZCodeSessionSettingsFromConfigOptions(),
  305. ): IZCodeSessionService {
  306. const workspaceState = createZCodeWorkspaceState(settings);
  307. return {
  308. initializeWorkspace: vi.fn(async () => ({
  309. available: true,
  310. workspaceKey: workspaceState.workspace.workspaceKey,
  311. protocolName: ZCODE_PROTOCOL_NAME,
  312. protocolVersion: ZCODE_PROTOCOL_VERSION,
  313. transportKind: "stdio",
  314. })),
  315. readWorkspacePresentation: vi.fn(async () => ({
  316. workspace: workspaceState.workspace,
  317. mode: workspaceState.settings.mode.current,
  318. slashCommands: [],
  319. })),
  320. updateProviderRegistry: vi.fn(async () => ({
  321. applied: true,
  322. revision: "test-provider-registry",
  323. })),
  324. } as unknown as IZCodeSessionService;
  325. }
  326. export function createBotsService(
  327. deps: Omit<
  328. Parameters<typeof createBotsServiceImpl>[0],
  329. "zcodeSessionService" | "zcodeTaskService" | "projectService"
  330. > & {
  331. zcodeTaskService?: IZCodeTaskService;
  332. /** 旧测试名保留为别名;真实注入的是 ZCode task service。 */
  333. legacyTaskService?: IZCodeTaskService;
  334. zcodeSessionService?: IZCodeSessionService;
  335. projectService?: Parameters<typeof createBotsServiceImpl>[0]["projectService"];
  336. },
  337. ): ReturnType<typeof createBotsServiceImpl> {
  338. const {
  339. legacyTaskService,
  340. zcodeTaskService: providedZCodeTaskService,
  341. zcodeSessionService: _providedZCodeSessionService,
  342. ...rest
  343. } = deps;
  344. const zcodeTaskService =
  345. providedZCodeTaskService ?? legacyTaskService ?? createLegacyTaskService();
  346. const modelSelectionService =
  347. deps.modelSelectionService ??
  348. createModelSelectionService([{ id: "glm", name: "GLM", models: ["default"] }]);
  349. return createBotsServiceImpl({
  350. ...createBotProjectServices(undefined, (target) => zcodeTaskService.listTasks(target)),
  351. settingService: createSettingService({
  352. locale: "zh-CN",
  353. lastWorkspaceSession: [
  354. {
  355. kind: "remote",
  356. workspacePath: "/tmp/workspace",
  357. workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
  358. },
  359. ],
  360. }),
  361. remoteWorkspaceService: {
  362. isConnected: vi.fn(async () => true),
  363. ensureConnected: vi.fn(async () => ({ ok: true })),
  364. getZCodeTaskService: vi.fn(async () => zcodeTaskService),
  365. getModelSelectionService: vi.fn(async () => modelSelectionService),
  366. },
  367. modelSelectionService,
  368. ...rest,
  369. zcodeTaskService,
  370. });
  371. }
  372. /** 显式项目服务夹具;生产候选不得从 settings/tab 历史恢复。 */
  373. export function createBotProjectServices(
  374. workspaces = [
  375. {
  376. workspacePath: "/tmp/workspace",
  377. workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
  378. } as { workspacePath: string; workspaceIdentity?: string },
  379. ],
  380. readTasks?: (target: {
  381. workspacePath: string;
  382. workspaceIdentity?: string;
  383. }) => ReturnType<IZCodeTaskService["listTasks"]>,
  384. ) {
  385. const projects: VirtualProject[] = workspaces.map((workspace, index) => ({
  386. id: `project-${index}`,
  387. hostId: workspace.workspaceIdentity
  388. ? remoteHostIdFromWorkspaceIdentity(workspace.workspaceIdentity)!
  389. : "local",
  390. name: workspace.workspacePath.split("/").at(-1)!,
  391. roots: [{ rootPath: workspace.workspacePath, position: 0, isPrimary: true }],
  392. nameOverridden: false,
  393. position: index,
  394. pinned: false,
  395. deleted: false,
  396. createdAt: 1,
  397. updatedAt: 1,
  398. }));
  399. const hosts = [
  400. ...new Set(projects.map((project) => project.hostId).filter((id) => id !== "local")),
  401. ];
  402. return {
  403. projectService: {
  404. readTree: vi.fn(async (input?: { hostId?: string }) => ({
  405. projects: projects.filter((project) => project.hostId === (input?.hostId ?? "local")),
  406. tasks: (
  407. await Promise.all(
  408. projects.map(async (project, index) =>
  409. project.hostId !== (input?.hostId ?? "local")
  410. ? []
  411. : ((await readTasks?.(workspaces[index]!)) ?? []).map((task) => ({
  412. ...task,
  413. projectId: project.id,
  414. hostId: project.hostId,
  415. pinned: false,
  416. archived: false,
  417. })),
  418. ),
  419. )
  420. ).flat(),
  421. })),
  422. readProjects: vi.fn(async (input?: { hostId?: string }) =>
  423. projects.filter((project) => project.hostId === (input?.hostId ?? "local")),
  424. ),
  425. prepareSession: vi.fn(async (input?: { projectId?: string; hostId?: string }) => {
  426. const index = projects.findIndex(
  427. (project) =>
  428. project.id === input?.projectId && project.hostId === (input?.hostId ?? "local"),
  429. );
  430. if (index < 0) throw new Error("project missing");
  431. return { ...workspaces[index]!, projectId: projects[index]!.id, additionalDirectories: [] };
  432. }),
  433. },
  434. remoteProjectService: {
  435. readDirectory: vi.fn(async () => ({
  436. hosts: hosts.map((id) => ({
  437. id,
  438. membershipId: id,
  439. kind: "server" as const,
  440. target: null,
  441. position: 0,
  442. connectionStatus: "online" as const,
  443. })),
  444. entries: projects
  445. .filter((project) => project.hostId !== "local")
  446. .map((project) => ({
  447. id: project.id,
  448. projectId: project.id,
  449. hostId: project.hostId,
  450. name: project.name,
  451. roots: project.roots,
  452. legacyWorkspace: null,
  453. lastSyncedAt: 1,
  454. })),
  455. })),
  456. },
  457. };
  458. }
  459. export const baseConfig: BotsConfigFile = {
  460. version: 3,
  461. bots: [
  462. {
  463. id: "webhook-1",
  464. name: "Webhook",
  465. provider: "webhook",
  466. enabled: true,
  467. webhookSecretRef: "secret-1",
  468. allowedWorkspaces: ["*"],
  469. allowedCommands: defaultUserCommands,
  470. currentOptions: {},
  471. replyMode: "assistant_changes",
  472. },
  473. ],
  474. };
  475. export const telegramConfig: BotsConfigFile = {
  476. ...baseConfig,
  477. bots: [
  478. {
  479. ...baseConfig.bots[0]!,
  480. id: "telegram-1",
  481. name: "Telegram",
  482. provider: "telegram",
  483. credentialRef: "telegram-token",
  484. webhookSecretRef: undefined,
  485. providerUserId: "user-1",
  486. allowedWorkspaces: ["*"],
  487. },
  488. ],
  489. };
  490. export const feishuConfig: BotsConfigFile = {
  491. ...baseConfig,
  492. bots: [
  493. {
  494. ...baseConfig.bots[0]!,
  495. id: "feishu-1",
  496. name: "Feishu",
  497. provider: "feishu",
  498. credentialRef: "feishu-secret",
  499. webhookSecretRef: undefined,
  500. feishuAppId: "cli_xxx",
  501. providerUserId: "ou_user",
  502. allowedWorkspaces: ["*"],
  503. },
  504. ],
  505. };
  506. export const weixinConfig: BotsConfigFile = {
  507. ...baseConfig,
  508. bots: [
  509. {
  510. ...baseConfig.bots[0]!,
  511. id: "weixin-1",
  512. name: "Weixin",
  513. provider: "weixin",
  514. credentialRef: "weixin-token",
  515. webhookSecretRef: undefined,
  516. allowedWorkspaces: ["*"],
  517. },
  518. ],
  519. };