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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 = { load: async () => null, save: async () => {}, delete: async () => {} };
  70. const directory = new SourceServerDirectory({ settingService, credentialService: credentials });
  71. let connections = 0;
  72. const registry = createWindowRemoteConnectionRegistry({
  73. createId: () => "session-e2e",
  74. resolveSourceServerId: () => "a1111111-1111-4111-8111-111111111111",
  75. connect: async () => {
  76. connections += 1;
  77. return { services: {}, dispose() {} };
  78. },
  79. });
  80. await registry.connect({
  81. requestId: "connect-e2e",
  82. target,
  83. remoteAssets: {},
  84. workspacePath: path,
  85. workspaceIdentity: stable,
  86. });
  87. const remoteCalls: unknown[] = [];
  88. const remoteScopes: unknown[] = [];
  89. let onRemotePrompt: (() => void) | undefined;
  90. const view = createBotModelSelectionView();
  91. const selected = view.preferredSelection!;
  92. const taskService = {
  93. resumeTask: async () => ({
  94. taskId: "remote-task",
  95. title: "Remote task",
  96. workspacePath: path,
  97. workspaceIdentity: stable,
  98. provider: "glm",
  99. }),
  100. listTasks: async () => [
  101. {
  102. taskId: "remote-task",
  103. title: "Remote task",
  104. workspacePath: path,
  105. workspaceIdentity: stable,
  106. provider: "glm",
  107. },
  108. ],
  109. listDeletedTaskIds: async (input: unknown) => {
  110. remoteScopes.push(input);
  111. return [];
  112. },
  113. getTaskModelSelection: async () => selected,
  114. getTaskConfigOptions: async () => [],
  115. getTaskSnapshot: async () => null,
  116. sendPrompt: async (input: unknown) => {
  117. remoteCalls.push(input);
  118. onRemotePrompt?.();
  119. },
  120. onDynamicTaskEvent: () => () => ({ dispose() {} }),
  121. onDynamicStreamEvent: () => () => ({ dispose() {} }),
  122. };
  123. const hostId = "remote:server:a1111111-1111-4111-8111-111111111111";
  124. const projectSelection = JSON.stringify([hostId, "e2e-project-0"]);
  125. const bound: string[] = [];
  126. const connection = {
  127. owner: {},
  128. taskService: taskService as unknown as IZCodeTaskService,
  129. modelSelectionService: { getView: async () => ({ ...view, effectiveSelection: selected }) },
  130. agentService: { syncAppRuntimePreferences: async () => {} },
  131. bindWorkspace: async (workspace: { workspaceIdentity: string }) => {
  132. bound.push(workspace.workspaceIdentity);
  133. },
  134. };
  135. const bridge = {
  136. ...createBotProjectRuntime({
  137. remoteProjectService: {
  138. readDirectory: async () => ({
  139. hosts: [{ id: hostId, membershipId: "m", kind: "ssh", target, position: 0 }],
  140. entries: [],
  141. }),
  142. connectHost: async () => {
  143. throw new Error("ordinary Bot input must not create a connection");
  144. },
  145. },
  146. resolveOnline: (id) => (id === hostId ? connection : undefined),
  147. onConnectionsChanged: () => ({ dispose() {} }),
  148. readBoundTargets: async () => [],
  149. readRuntimePreferences: async () => ({ askUserQuestionAutoResolutionEnabled: false }),
  150. warn: () => {},
  151. }),
  152. resolveWorkspace: (workspace: { workspacePath: string; workspaceIdentity: string }) =>
  153. resolveBotRemoteWorkspace(workspace, "lookup", {
  154. directory,
  155. listSessions: () => registry.listSessions(),
  156. }),
  157. };
  158. try {
  159. for (const identity of [legacy, stable]) {
  160. const delivered = new Promise<void>((resolve) => {
  161. onRemotePrompt = resolve;
  162. });
  163. const config: BotsConfigFile = {
  164. version: 3,
  165. bots: [
  166. {
  167. id: "webhook-e2e",
  168. name: "Synthetic",
  169. provider: "webhook",
  170. enabled: true,
  171. providerUserId: "user-e2e",
  172. webhookSecretRef: "synthetic",
  173. allowedWorkspaces: [legacy],
  174. allowedCommands: {
  175. status: true,
  176. new: true,
  177. workspace: true,
  178. model: true,
  179. thoughtLevel: true,
  180. sandboxMode: true,
  181. approvalPolicy: true,
  182. reply: true,
  183. },
  184. currentOptions: {},
  185. replyMode: "assistant_changes",
  186. },
  187. ],
  188. };
  189. const harness = createBotsServiceHarness({
  190. config,
  191. remoteWorkspaceService: bridge,
  192. projectWorkspaces: [{ kind: "remote", workspacePath: path, workspaceIdentity: stable }],
  193. state: {
  194. version: 3,
  195. bots: {
  196. "webhook-e2e": {
  197. botId: "webhook-e2e",
  198. // hostId 是已迁移上下文的标记;旧身份夹具不能同时伪造新版字段而跳过迁移。
  199. ...(identity === legacy ? {} : { projectId: "e2e-project-0", hostId }),
  200. workspacePath: path,
  201. workspaceIdentity: identity,
  202. workspaceId: identity === legacy ? legacy : projectSelection,
  203. mode: "task",
  204. activeTaskId: "remote-task",
  205. updatedAt: 1,
  206. },
  207. },
  208. },
  209. });
  210. try {
  211. const replies = await harness.service.handleInboundMessage({
  212. botId: "webhook-e2e",
  213. actor: {
  214. provider: "webhook",
  215. botId: "webhook-e2e",
  216. providerUserId: "user-e2e",
  217. chatType: "private",
  218. },
  219. text: "E2E_BOT_R3_IDENTITY 检查项目",
  220. });
  221. expect(replies.map((reply) => reply.text ?? "").join("\n")).not.toMatch(
  222. /未连接|已不在授权范围/u,
  223. );
  224. let deliveryTimer: ReturnType<typeof setTimeout> | undefined;
  225. try {
  226. await Promise.race([
  227. delivered,
  228. new Promise<never>((_resolve, reject) => {
  229. deliveryTimer = setTimeout(
  230. () => reject(new Error(`E2E_BOT_R3_IDENTITY: ${identity} 没有投递到远端 runtime`)),
  231. 15_000,
  232. );
  233. }),
  234. ]);
  235. } finally {
  236. if (deliveryTimer) clearTimeout(deliveryTimer);
  237. }
  238. expect(harness.sendPromptCalls).toEqual([]);
  239. expect(harness.createTaskCalls).toEqual([]);
  240. expect(harness.readState().bots["webhook-e2e"]?.workspaceIdentity).toBe(stable);
  241. // 授权键属于项目选择,workspaceIdentity 才是规范化后的执行身份。
  242. expect((await harness.service.getConfig()).bots[0]!.allowedWorkspaces).toEqual([
  243. projectSelection,
  244. ]);
  245. expect(harness.readState().bots["webhook-e2e"]).toMatchObject({
  246. hostId,
  247. projectId: "e2e-project-0",
  248. workspaceId: projectSelection,
  249. });
  250. } finally {
  251. await harness.service.disposeAllAndWait();
  252. }
  253. }
  254. expect(remoteCalls).toHaveLength(2);
  255. for (const call of remoteCalls) expect(call).toMatchObject({ taskId: "remote-task" });
  256. expect(remoteScopes).toHaveLength(2);
  257. for (const scope of remoteScopes)
  258. expect(scope).toMatchObject({ workspacePath: path, workspaceIdentity: stable });
  259. expect(bound.length).toBeGreaterThan(0);
  260. expect(bound.every((identity) => identity === stable)).toBe(true);
  261. expect(connections).toBe(1);
  262. const artifactDir = resolve(
  263. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/bot-r3-workspace-identity",
  264. );
  265. await mkdir(artifactDir, { recursive: true });
  266. await writeFile(
  267. resolve(artifactDir, "bot-identity.json"),
  268. JSON.stringify(
  269. {
  270. caseId: "BOT-E2E-RW-02",
  271. synthetic: true,
  272. stable,
  273. legacy,
  274. remotePrompts: remoteCalls.length,
  275. sharedHostBindings: bound.length,
  276. connections,
  277. localPrompts: 0,
  278. },
  279. null,
  280. 2,
  281. ),
  282. );
  283. } finally {
  284. await registry.dispose();
  285. }
  286. });