bot-r3-workspace-identity.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { type IZCodeTaskService, type ISettingService } from "@zcode/services";
  4. import {
  5. appSettingsSchema,
  6. buildRemoteWorkspaceIdentity,
  7. buildServerRemoteWorkspaceIdentity,
  8. type BotsConfigFile,
  9. } from "@zcode/shared";
  10. import { createBotProjectRuntime } from "../../../../../services/src/bot-project-runtime/index.js";
  11. import { SourceServerDirectory } from "#src/host/sourceServerDirectory.js";
  12. import { resolveBotRemoteWorkspace } from "#src/host/botRemoteWorkspaceResolver.js";
  13. import { createWindowRemoteConnectionRegistry } from "#src/host/windowRemoteConnectionRegistry.js";
  14. import {
  15. createBotModelSelectionView,
  16. createBotsServiceHarness,
  17. readBotSyntheticFixture,
  18. } from "#e2e/bots/helpers/bots-service-harness";
  19. it("BOT-E2E-RW-02 legacy 与 stable Bot 通过同一 Source 身份完成任务路由", async () => {
  20. expect(await readBotSyntheticFixture("r3-workspace-identity.json")).toMatchObject({
  21. caseId: "BOT-E2E-RW-02",
  22. classification: "synthetic",
  23. });
  24. const path = "/work/bot";
  25. const target = { kind: "ssh" as const, host: "synthetic.invalid", username: "dev" };
  26. const stable = buildServerRemoteWorkspaceIdentity({
  27. serverId: "a1111111-1111-4111-8111-111111111111",
  28. workspacePath: path,
  29. });
  30. const legacy = buildRemoteWorkspaceIdentity(path, target);
  31. let settings = appSettingsSchema.parse({
  32. sourceServerDirectoryMigrationVersion: 1,
  33. sourceServers: [
  34. {
  35. sourceServerId: "a1111111-1111-4111-8111-111111111111",
  36. displayName: "Synthetic Source",
  37. preferredProfileId: "b2222222-2222-4222-8222-222222222222",
  38. },
  39. ],
  40. connectionProfiles: [
  41. {
  42. profileId: "b2222222-2222-4222-8222-222222222222",
  43. sourceServerId: "a1111111-1111-4111-8111-111111111111",
  44. transport: "ssh",
  45. target,
  46. createdAt: 1,
  47. },
  48. ],
  49. lastWorkspaceSession: [
  50. {
  51. kind: "remote",
  52. workspacePath: path,
  53. workspaceIdentity: legacy,
  54. target,
  55. lastOpenedAt: 1,
  56. lastConnectionStatus: "connected",
  57. },
  58. ],
  59. });
  60. const settingService: ISettingService = {
  61. get: async () => settings,
  62. update: async (patch) => {
  63. settings = appSettingsSchema.parse({ ...settings, ...patch });
  64. },
  65. updateDataBaseDir: async () => {},
  66. getUserInstructions: async () => ({ content: "", filePath: "" }),
  67. saveUserInstructions: async () => ({ filePath: "" }),
  68. };
  69. const credentials = {
  70. load: async () => null,
  71. save: async () => {},
  72. delete: async () => {},
  73. inspectStore: async () => ({ status: "healthy" as const }),
  74. recoverStore: async () => ({ status: "changed" as const }),
  75. };
  76. const directory = new SourceServerDirectory({ settingService, credentialService: credentials });
  77. let connections = 0;
  78. const registry = createWindowRemoteConnectionRegistry({
  79. createId: () => "session-e2e",
  80. resolveSourceServerId: () => "a1111111-1111-4111-8111-111111111111",
  81. connect: async () => {
  82. connections += 1;
  83. return { services: {}, dispose() {} };
  84. },
  85. });
  86. await registry.connect({
  87. requestId: "connect-e2e",
  88. target,
  89. remoteAssets: {},
  90. workspacePath: path,
  91. workspaceIdentity: stable,
  92. });
  93. const remoteCalls: unknown[] = [];
  94. const remoteScopes: unknown[] = [];
  95. let onRemotePrompt: (() => void) | undefined;
  96. const view = createBotModelSelectionView();
  97. const selected = view.preferredSelection!;
  98. const taskService = {
  99. resumeTask: async () => ({
  100. taskId: "remote-task",
  101. title: "Remote task",
  102. workspacePath: path,
  103. workspaceIdentity: stable,
  104. provider: "glm",
  105. }),
  106. listTasks: async () => [
  107. {
  108. taskId: "remote-task",
  109. title: "Remote task",
  110. workspacePath: path,
  111. workspaceIdentity: stable,
  112. provider: "glm",
  113. },
  114. ],
  115. listDeletedTaskIds: async (input: unknown) => {
  116. remoteScopes.push(input);
  117. return [];
  118. },
  119. getTaskModelSelection: async () => selected,
  120. getTaskConfigOptions: async () => [],
  121. getTaskSnapshot: async () => null,
  122. sendPrompt: async (input: unknown) => {
  123. remoteCalls.push(input);
  124. onRemotePrompt?.();
  125. },
  126. onDynamicTaskEvent: () => () => ({ dispose() {} }),
  127. onDynamicStreamEvent: () => () => ({ dispose() {} }),
  128. };
  129. const hostId = "remote:server:a1111111-1111-4111-8111-111111111111";
  130. const projectSelection = JSON.stringify([hostId, "e2e-project-0"]);
  131. const bound: string[] = [];
  132. const connection = {
  133. owner: {},
  134. taskService: taskService as unknown as IZCodeTaskService,
  135. modelSelectionService: { getView: async () => ({ ...view, effectiveSelection: selected }) },
  136. agentService: { syncAppRuntimePreferences: async () => {} },
  137. bindWorkspace: async (workspace: { workspaceIdentity: string }) => {
  138. bound.push(workspace.workspaceIdentity);
  139. },
  140. };
  141. const bridge = {
  142. ...createBotProjectRuntime({
  143. remoteProjectService: {
  144. readDirectory: async () => ({
  145. hosts: [{ id: hostId, membershipId: "m", kind: "ssh", target, position: 0 }],
  146. entries: [],
  147. }),
  148. connectHost: async () => {
  149. throw new Error("ordinary Bot input must not create a connection");
  150. },
  151. },
  152. resolveOnline: (id) => (id === hostId ? connection : undefined),
  153. onConnectionsChanged: () => ({ dispose() {} }),
  154. readBoundTargets: async () => [],
  155. readRuntimePreferences: async () => ({ askUserQuestionAutoResolutionEnabled: false }),
  156. warn: () => {},
  157. }),
  158. resolveWorkspace: (workspace: { workspacePath: string; workspaceIdentity: string }) =>
  159. resolveBotRemoteWorkspace(workspace, "lookup", {
  160. directory,
  161. listSessions: () => registry.listSessions(),
  162. }),
  163. };
  164. try {
  165. for (const identity of [legacy, stable]) {
  166. const delivered = new Promise<void>((resolve) => {
  167. onRemotePrompt = resolve;
  168. });
  169. const config: BotsConfigFile = {
  170. version: 3,
  171. bots: [
  172. {
  173. id: "webhook-e2e",
  174. name: "Synthetic",
  175. provider: "webhook",
  176. enabled: true,
  177. providerUserId: "user-e2e",
  178. webhookSecretRef: "synthetic",
  179. allowedWorkspaces: [legacy],
  180. allowedCommands: {
  181. status: true,
  182. new: true,
  183. workspace: true,
  184. model: true,
  185. thoughtLevel: true,
  186. sandboxMode: true,
  187. approvalPolicy: true,
  188. reply: true,
  189. },
  190. currentOptions: {},
  191. replyMode: "assistant_changes",
  192. },
  193. ],
  194. };
  195. const harness = createBotsServiceHarness({
  196. config,
  197. remoteWorkspaceService: bridge,
  198. projectWorkspaces: [{ kind: "remote", workspacePath: path, workspaceIdentity: stable }],
  199. state: {
  200. version: 3,
  201. bots: {
  202. "webhook-e2e": {
  203. botId: "webhook-e2e",
  204. // hostId 是已迁移上下文的标记;旧身份夹具不能同时伪造新版字段而跳过迁移。
  205. ...(identity === legacy ? {} : { projectId: "e2e-project-0", hostId }),
  206. workspacePath: path,
  207. workspaceIdentity: identity,
  208. workspaceId: identity === legacy ? legacy : projectSelection,
  209. mode: "task",
  210. activeTaskId: "remote-task",
  211. updatedAt: 1,
  212. },
  213. },
  214. },
  215. });
  216. try {
  217. const replies = await harness.service.handleInboundMessage({
  218. botId: "webhook-e2e",
  219. actor: {
  220. provider: "webhook",
  221. botId: "webhook-e2e",
  222. providerUserId: "user-e2e",
  223. chatType: "private",
  224. },
  225. text: "E2E_BOT_R3_IDENTITY 检查项目",
  226. });
  227. expect(replies.map((reply) => reply.text ?? "").join("\n")).not.toMatch(
  228. /未连接|已不在授权范围/u,
  229. );
  230. let deliveryTimer: ReturnType<typeof setTimeout> | undefined;
  231. try {
  232. await Promise.race([
  233. delivered,
  234. new Promise<never>((_resolve, reject) => {
  235. deliveryTimer = setTimeout(
  236. () => reject(new Error(`E2E_BOT_R3_IDENTITY: ${identity} 没有投递到远端 runtime`)),
  237. 15_000,
  238. );
  239. }),
  240. ]);
  241. } finally {
  242. if (deliveryTimer) clearTimeout(deliveryTimer);
  243. }
  244. expect(harness.sendPromptCalls).toEqual([]);
  245. expect(harness.createTaskCalls).toEqual([]);
  246. expect(harness.readState().bots["webhook-e2e"]?.workspaceIdentity).toBe(stable);
  247. // 授权键属于项目选择,workspaceIdentity 才是规范化后的执行身份。
  248. expect((await harness.service.getConfig()).bots[0]!.allowedWorkspaces).toEqual([
  249. projectSelection,
  250. ]);
  251. expect(harness.readState().bots["webhook-e2e"]).toMatchObject({
  252. hostId,
  253. projectId: "e2e-project-0",
  254. workspaceId: projectSelection,
  255. });
  256. } finally {
  257. await harness.service.disposeAllAndWait();
  258. }
  259. }
  260. expect(remoteCalls).toHaveLength(2);
  261. for (const call of remoteCalls) expect(call).toMatchObject({ taskId: "remote-task" });
  262. expect(remoteScopes).toHaveLength(2);
  263. for (const scope of remoteScopes)
  264. expect(scope).toMatchObject({ workspacePath: path, workspaceIdentity: stable });
  265. expect(bound.length).toBeGreaterThan(0);
  266. expect(bound.every((identity) => identity === stable)).toBe(true);
  267. expect(connections).toBe(1);
  268. const artifactDir = resolve(
  269. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/bot-r3-workspace-identity",
  270. );
  271. await mkdir(artifactDir, { recursive: true });
  272. await writeFile(
  273. resolve(artifactDir, "bot-identity.json"),
  274. JSON.stringify(
  275. {
  276. caseId: "BOT-E2E-RW-02",
  277. synthetic: true,
  278. stable,
  279. legacy,
  280. remotePrompts: remoteCalls.length,
  281. sharedHostBindings: bound.length,
  282. connections,
  283. localPrompts: 0,
  284. },
  285. null,
  286. 2,
  287. ),
  288. );
  289. } finally {
  290. await registry.dispose();
  291. }
  292. });