bots-service-harness.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import { remoteHostIdFromWorkspaceIdentity } from "@zcode/shared";
  2. import { readFile } from "node:fs/promises";
  3. import type { ModelSelectionView } from "@zcode/provider";
  4. import type {
  5. BotsConfigFile,
  6. BotsStateFile,
  7. ModelSelection,
  8. ZCodeStreamEvent,
  9. } from "@zcode/shared";
  10. import { createBotsService, type IModelSelectionService } from "@zcode/services/node";
  11. import { resolveE2ERuntimePath } from "../../helpers/e2e-runtime-paths.js";
  12. const E2E_BOT_WORKSPACE = resolveE2ERuntimePath("bots", "e2e-bot-workspace");
  13. export interface RecordedRequest {
  14. url: string;
  15. method: string;
  16. body?: string;
  17. }
  18. export interface BotSyntheticFixture {
  19. caseId: string;
  20. classification: "synthetic";
  21. syntheticReason: string;
  22. timing: string;
  23. promptMarker?: string;
  24. }
  25. export async function readBotSyntheticFixture(filename: string): Promise<BotSyntheticFixture> {
  26. const url = new URL(`../../fixtures/bots/${filename}`, import.meta.url);
  27. return JSON.parse(await readFile(url, "utf8")) as BotSyntheticFixture;
  28. }
  29. export interface BotsServiceHarnessOptions {
  30. config: BotsConfigFile;
  31. state?: BotsStateFile;
  32. modelSelectionService?: Pick<IModelSelectionService, "getView">;
  33. fetch?: typeof fetch;
  34. remoteWorkspaceService?: Record<string, unknown>;
  35. runStartupBackgroundTasks?: boolean;
  36. broadcastService?: { send(message: unknown): Promise<void> };
  37. projectWorkspaces?: Array<
  38. Record<string, unknown> & { kind: "local" | "remote"; workspacePath: string }
  39. >;
  40. }
  41. export interface BotsServiceHarness {
  42. createTaskCalls: unknown[];
  43. readState: () => BotsStateFile;
  44. respondElicitationCalls: unknown[];
  45. sendPromptCalls: unknown[];
  46. service: ReturnType<typeof createBotsService>;
  47. subscriptions: Array<{
  48. params: Record<string, unknown>;
  49. listener: (event: ZCodeStreamEvent) => Promise<void> | void;
  50. }>;
  51. zcodeTaskService: Record<string, unknown>;
  52. }
  53. export function createBotModelSelectionView(): ModelSelectionView {
  54. const providerId = "bot-e2e-provider";
  55. const modelId = "bot-e2e-model";
  56. return {
  57. revision: 1,
  58. preferredSelection: { providerId, modelId },
  59. providers: [
  60. {
  61. providerId,
  62. providerName: "Bot E2E Provider",
  63. config: {
  64. api: {
  65. type: "anthropic-messages",
  66. baseUrl: "https://example.invalid/v1",
  67. },
  68. personalModelIds: [modelId],
  69. },
  70. models: [
  71. {
  72. modelId,
  73. config: {
  74. enabled: true,
  75. properties: {
  76. requiresMfjsToolSchema: false,
  77. contextWindow: 128_000,
  78. inputFormat: {
  79. supportsText: true,
  80. supportsImage: false,
  81. supportsVideo: false,
  82. supportsAudio: false,
  83. supportsPdf: false,
  84. },
  85. outputFormat: { supportsText: true },
  86. supportsToolCall: true,
  87. supportsJsonSchemaOutput: true,
  88. supportsNativeWebSearch: false,
  89. supportsMidConversationSystem: false,
  90. },
  91. optionSpecs: {
  92. reasoningLevel: { values: ["disabled"], map: "{}" },
  93. maxOutputTokens: {
  94. max: 8_192,
  95. map: '{"max_completion_tokens":maxOutputTokens}',
  96. },
  97. },
  98. },
  99. },
  100. ],
  101. },
  102. ],
  103. };
  104. }
  105. export function createBotsServiceHarness(options: BotsServiceHarnessOptions): BotsServiceHarness {
  106. let config = options.config;
  107. let state: BotsStateFile = options.state ?? { version: 3, bots: {} };
  108. const createTaskCalls: unknown[] = [];
  109. let taskModelSelection: ModelSelection | null = null;
  110. const sendPromptCalls: unknown[] = [];
  111. const respondElicitationCalls: unknown[] = [];
  112. const subscriptions: Array<{
  113. params: Record<string, unknown>;
  114. listener: (event: ZCodeStreamEvent) => Promise<void> | void;
  115. }> = [];
  116. const zcodeTaskService = {
  117. listTasks: async () => [],
  118. listDeletedTaskIds: async () => [],
  119. createTask: async (params: unknown) => {
  120. createTaskCalls.push(params);
  121. taskModelSelection = (params as { modelSelection?: ModelSelection }).modelSelection ?? null;
  122. return {
  123. taskId: "task-e2e-bot",
  124. title: "E2E Bot Task",
  125. workspacePath: E2E_BOT_WORKSPACE,
  126. provider: "glm",
  127. };
  128. },
  129. sendPrompt: async (params: unknown) => {
  130. sendPromptCalls.push(params);
  131. },
  132. setMode: async () => undefined,
  133. setConfigOption: async () => [],
  134. setModel: async (params: { modelSelection: ModelSelection }) => {
  135. taskModelSelection = params.modelSelection;
  136. return [];
  137. },
  138. setAutomationSessionConfig: async () => [],
  139. getTaskConfigOptions: async () => [],
  140. getTaskModelSelection: async () => taskModelSelection,
  141. getTaskSnapshot: async () => null,
  142. getTaskTokenUsage: async () => ({
  143. sessionId: "task-e2e-bot",
  144. totalTokens: 0,
  145. inputTokens: 0,
  146. outputTokens: 0,
  147. reasoningTokens: 0,
  148. cacheCreationTokens: 0,
  149. cacheReadTokens: 0,
  150. modelRequestCount: 0,
  151. modelErrorCount: 0,
  152. inputBaselineBySource: {},
  153. }),
  154. resumeTask: async () => ({
  155. taskId: "task-e2e-bot",
  156. title: "E2E Bot Task",
  157. workspacePath: E2E_BOT_WORKSPACE,
  158. provider: "glm",
  159. }),
  160. respondPermission: async () => true,
  161. respondElicitation: async (params: unknown) => {
  162. respondElicitationCalls.push(params);
  163. return true;
  164. },
  165. stopGeneration: async () => undefined,
  166. onDynamicTaskEvent:
  167. (params: Record<string, unknown>) =>
  168. (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  169. subscriptions.push({ params, listener });
  170. return { dispose() {} };
  171. },
  172. onDynamicStreamEvent: () => () => ({ dispose() {} }),
  173. };
  174. const service = createBotsService({
  175. ...createBotProjectFixture(options.projectWorkspaces),
  176. credentialService: {
  177. load: async () => "app-secret-e2e",
  178. save: async () => undefined,
  179. delete: async () => undefined,
  180. },
  181. zcodeTaskService,
  182. settingService: {
  183. get: async () => ({
  184. locale: "zh-CN",
  185. recentProjects: [E2E_BOT_WORKSPACE],
  186. lastWorkspaceSession: [],
  187. enabledBuiltinAgentCliProviders: ["glm"],
  188. }),
  189. update: async () => undefined,
  190. updateDataBaseDir: async () => undefined,
  191. },
  192. repo: {
  193. readConfig: async () => config,
  194. writeConfig: async (next: BotsConfigFile) => (config = next),
  195. readState: async () => state,
  196. writeState: async (next: BotsStateFile) => (state = next),
  197. updateContext: async (
  198. botId: string,
  199. update: (
  200. current: BotsStateFile["bots"][string] | undefined,
  201. ) => BotsStateFile["bots"][string] | undefined,
  202. ) => {
  203. const next = update(state.bots[botId]);
  204. if (next) state.bots[botId] = next;
  205. else delete state.bots[botId];
  206. return next;
  207. },
  208. },
  209. modelSelectionService: options.modelSelectionService ?? {
  210. getView: async () => createBotModelSelectionView(),
  211. },
  212. remoteWorkspaceService: options.remoteWorkspaceService,
  213. broadcastService: options.broadcastService,
  214. runStartupBackgroundTasks: options.runStartupBackgroundTasks ?? false,
  215. warmCandidateCachesOnStartup: false,
  216. } as never);
  217. return {
  218. createTaskCalls,
  219. readState: () => structuredClone(state),
  220. respondElicitationCalls,
  221. sendPromptCalls,
  222. service,
  223. subscriptions,
  224. zcodeTaskService,
  225. };
  226. }
  227. export function createFeishuConfig(
  228. provider: "feishu" | "lark" = "feishu",
  229. id = `${provider}-e2e`,
  230. ): BotsConfigFile {
  231. return {
  232. version: 3,
  233. bots: [
  234. {
  235. id,
  236. name: `${provider} E2E`,
  237. provider,
  238. enabled: true,
  239. credentialRef: `${provider}-secret`,
  240. feishuAppId: `${provider}-app-e2e`,
  241. providerUserId: "ou_e2e_user",
  242. allowedWorkspaces: ["*"],
  243. allowedCommands: {
  244. status: true,
  245. new: true,
  246. workspace: true,
  247. model: true,
  248. thoughtLevel: true,
  249. sandboxMode: true,
  250. approvalPolicy: true,
  251. reply: true,
  252. },
  253. currentOptions: {},
  254. replyMode: "streaming_card",
  255. },
  256. ],
  257. };
  258. }
  259. export function createFeishuCallback(botId: string, text: string) {
  260. return {
  261. botId,
  262. event: {
  263. sender: { sender_id: { open_id: "ou_e2e_user" } },
  264. message: {
  265. chat_id: "oc_e2e_private",
  266. message_id: `om_${botId}_inbound`,
  267. chat_type: "p2p",
  268. message_type: "text",
  269. content: JSON.stringify({ text }),
  270. },
  271. },
  272. };
  273. }
  274. export function createRecordingFeishuFetch(requests: RecordedRequest[]): typeof fetch {
  275. return async (input, init) => {
  276. const url = String(input);
  277. const method = init?.method ?? "GET";
  278. requests.push({
  279. url,
  280. method,
  281. ...(typeof init?.body === "string" ? { body: init.body } : {}),
  282. });
  283. if (url.endsWith("/tenant_access_token/internal")) {
  284. return new Response(JSON.stringify({ code: 0, tenant_access_token: "token-e2e" }));
  285. }
  286. if (url.includes("/open-apis/im/v1/messages")) {
  287. return new Response(JSON.stringify({ code: 0, data: { message_id: "om_e2e_card" } }));
  288. }
  289. if (url.includes("/reactions") && method === "POST") {
  290. return new Response(JSON.stringify({ code: 0, data: { reaction_id: "reaction-e2e" } }));
  291. }
  292. if (url.includes("/contact/v3/users/")) {
  293. return new Response(JSON.stringify({ code: 0, data: { user: { name: "E2E User" } } }));
  294. }
  295. return new Response(JSON.stringify({ code: 0 }));
  296. };
  297. }
  298. /** case-local 项目事实;不依赖真实 settings 历史或在线 runtime。 */
  299. export function createBotProjectFixture(
  300. workspaces: Array<{ workspacePath: string; workspaceIdentity?: unknown; projectId?: unknown }> = [
  301. { workspacePath: E2E_BOT_WORKSPACE },
  302. ],
  303. ) {
  304. const projects = workspaces.map((workspace, index) => ({
  305. id: typeof workspace.projectId === "string" ? workspace.projectId : `e2e-project-${index}`,
  306. hostId:
  307. typeof workspace.workspaceIdentity === "string"
  308. ? remoteHostIdFromWorkspaceIdentity(workspace.workspaceIdentity)!
  309. : "local",
  310. name: `E2E project ${index}`,
  311. roots: [{ rootPath: workspace.workspacePath, position: 0, isPrimary: true }],
  312. nameOverridden: false,
  313. position: index,
  314. pinned: false,
  315. deleted: false,
  316. createdAt: 1,
  317. updatedAt: 1,
  318. }));
  319. return {
  320. projectService: {
  321. readProjects: async (input?: { hostId?: string }) =>
  322. projects.filter((project) => project.hostId === (input?.hostId ?? "local")),
  323. readTree: async () => ({ projects, tasks: [] }),
  324. prepareSession: async (input: { projectId: string }) => {
  325. const index = projects.findIndex((project) => project.id === input.projectId);
  326. if (index < 0) throw new Error("fixture project missing");
  327. return { ...workspaces[index], projectId: input.projectId, additionalDirectories: [] };
  328. },
  329. },
  330. remoteProjectService: {
  331. readDirectory: async () => ({
  332. hosts: [
  333. ...new Set(projects.map((project) => project.hostId).filter((id) => id !== "local")),
  334. ].map((id) => ({
  335. id,
  336. membershipId: id,
  337. kind: "server",
  338. target: null,
  339. position: 0,
  340. connectionStatus: "online",
  341. })),
  342. entries: projects
  343. .filter((project) => project.hostId !== "local")
  344. .map((project) => ({
  345. id: project.id,
  346. projectId: project.id,
  347. hostId: project.hostId,
  348. name: project.name,
  349. roots: project.roots,
  350. legacyWorkspace: null,
  351. lastSyncedAt: 1,
  352. })),
  353. }),
  354. },
  355. };
  356. }