botsProjectBinding.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import { expect, it, vi } from "vitest";
  2. import * as f from "./botsService.fixtures.js";
  3. import type { VirtualProject, ProjectTask } from "../src/project/contract.js";
  4. const actor = {
  5. provider: "webhook" as const,
  6. botId: "webhook-1",
  7. providerUserId: "user-1",
  8. chatType: "private" as const,
  9. };
  10. const config = { ...f.baseConfig, bots: [{ ...f.baseConfig.bots[0]!, providerUserId: "user-1" }] };
  11. function project(id: string, roots = ["/first", "/extra"]): VirtualProject {
  12. return {
  13. id,
  14. hostId: "local",
  15. name: id,
  16. roots: roots.map((rootPath, position) => ({ rootPath, position, isPrimary: position === 0 })),
  17. nameOverridden: false,
  18. position: 0,
  19. pinned: false,
  20. deleted: false,
  21. createdAt: 1,
  22. updatedAt: 1,
  23. };
  24. }
  25. function setup(initial = [project("p")], state?: Parameters<typeof f.createMemoryRepo>[1]) {
  26. let projects = initial;
  27. let tasks: ProjectTask[] = [];
  28. const repo = f.createMemoryRepo(config, state);
  29. const task = f.createLegacyTaskService();
  30. const prepareSession = vi.fn(async (input?: { projectId?: string }) => {
  31. const selected = projects.find((item) => item.id === input?.projectId);
  32. if (!selected) throw new Error("project missing");
  33. return {
  34. projectId: selected.id,
  35. workspacePath: selected.roots[0]?.rootPath ?? "/allocated",
  36. additionalDirectories: selected.roots.slice(1).map((root) => root.rootPath),
  37. };
  38. });
  39. const service = f.createBotsService({
  40. repo: repo as never,
  41. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  42. zcodeTaskService: task,
  43. projectService: {
  44. readProjects: async () => projects,
  45. prepareSession,
  46. readTree: async () => ({ projects, tasks }),
  47. },
  48. } as Parameters<typeof f.createBotsService>[0]);
  49. return {
  50. service,
  51. repo,
  52. task,
  53. prepareSession,
  54. setTasks: (next: ProjectTask[]) => {
  55. tasks = next;
  56. vi.mocked(task.listTasks).mockResolvedValue(next);
  57. },
  58. setProjects: (next: VirtualProject[]) => {
  59. projects = next;
  60. },
  61. send: (text: string) => service.handleInboundMessage({ botId: "webhook-1", actor, text }),
  62. };
  63. }
  64. it("候选按项目区分相同 cwd,并且不从历史 tab 造候选", async () => {
  65. const s = setup([project("one"), project("two"), project("empty", [])]);
  66. try {
  67. const refs = await s.service.listWorkspaceRefs({
  68. currentWorkspace: { id: "tab", label: "tab", workspacePath: "/tab" },
  69. });
  70. expect(refs.map((ref) => ref.label)).toEqual(["one", "two", "empty"]);
  71. expect(new Set(refs.map((ref) => ref.id)).size).toBe(3);
  72. expect(s.prepareSession).not.toHaveBeenCalled();
  73. } finally {
  74. s.service.disposeAll();
  75. }
  76. });
  77. it("同 cwd 其他项目任务不进入 Bot 选择,旧菜单被移动后不能绕过归属校验", async () => {
  78. const s = setup([project("p"), project("other")]);
  79. const row = (taskId: string, projectId: string): ProjectTask => ({
  80. taskId,
  81. projectId,
  82. hostId: "local",
  83. title: taskId,
  84. provider: "zcode",
  85. workspacePath: "/first",
  86. archived: false,
  87. pinned: false,
  88. });
  89. try {
  90. s.setTasks([row("allowed", "p"), row("elsewhere", "other")]);
  91. const menu = await s.send("/task");
  92. expect(menu[0]?.selection?.options.map((option) => option.id)).toEqual(["allowed"]);
  93. s.setTasks([row("allowed", "other"), row("elsewhere", "other")]);
  94. await s.send("/task allowed");
  95. expect((await s.repo.readState()).bots["webhook-1"]?.activeTaskId).toBeNull();
  96. } finally {
  97. s.service.disposeAll();
  98. }
  99. });
  100. it("/task 切换保持项目授权 ID,之后 /new 仍保留原执行快照", async () => {
  101. const s = setup();
  102. try {
  103. const refs = await s.service.listWorkspaceRefs();
  104. await s.repo.writeConfig({
  105. ...config,
  106. bots: [{ ...config.bots[0]!, allowedWorkspaces: [refs[0]!.id] }],
  107. });
  108. s.setTasks([
  109. {
  110. taskId: "existing",
  111. projectId: "p",
  112. hostId: "local",
  113. title: "existing",
  114. provider: "zcode",
  115. workspacePath: "/first",
  116. archived: false,
  117. pinned: false,
  118. },
  119. ]);
  120. await s.send("/task existing");
  121. expect((await s.repo.readState()).bots["webhook-1"]?.workspaceId).toBe(refs[0]!.id);
  122. await s.send("/new");
  123. expect((await s.repo.readState()).bots["webhook-1"]).toMatchObject({
  124. mode: "draft",
  125. activeTaskId: null,
  126. additionalDirectories: ["/extra"],
  127. });
  128. } finally {
  129. s.service.disposeAll();
  130. }
  131. });
  132. it("首次绑定持久化目录,roots 编辑及 /new 后新建仍使用同一快照", async () => {
  133. const s = setup();
  134. try {
  135. await s.send("/status");
  136. expect((await s.repo.readState()).bots["webhook-1"]).toMatchObject({
  137. projectId: "p",
  138. hostId: "local",
  139. workspacePath: "/first",
  140. additionalDirectories: ["/extra"],
  141. });
  142. s.setProjects([project("p", ["/changed", "/changed-extra"])]);
  143. await s.send("/new");
  144. await s.send("hello");
  145. expect(s.task.createTask).toHaveBeenCalledWith(
  146. expect.objectContaining({
  147. projectId: "p",
  148. workspacePath: "/first",
  149. additionalDirectories: ["/extra"],
  150. }),
  151. );
  152. expect(s.prepareSession).toHaveBeenCalledTimes(1);
  153. } finally {
  154. s.service.disposeAll();
  155. }
  156. });
  157. it("旧 context cwd 不追随主要目录;明确 NULL 交接后不再次归入", async () => {
  158. const s = setup([project("one"), project("two")], {
  159. version: 3,
  160. bots: {
  161. "webhook-1": {
  162. botId: "webhook-1",
  163. workspacePath: "/first",
  164. mode: "draft",
  165. activeTaskId: null,
  166. updatedAt: 1,
  167. },
  168. },
  169. });
  170. try {
  171. await s.send("/status");
  172. expect((await s.repo.readState()).bots["webhook-1"]).toMatchObject({
  173. hostId: "local",
  174. projectId: null,
  175. workspacePath: "/first",
  176. additionalDirectories: [],
  177. });
  178. s.setProjects([project("one")]);
  179. await s.send("/status");
  180. expect((await s.repo.readState()).bots["webhook-1"]?.projectId).toBeNull();
  181. expect(s.prepareSession).not.toHaveBeenCalled();
  182. } finally {
  183. s.service.disposeAll();
  184. }
  185. });
  186. it("两个 Bot 同时创建绑定不能用整份旧 state 覆盖对方", async () => {
  187. const other = { ...config.bots[0]!, id: "webhook-2", providerUserId: "user-2" };
  188. const repo = f.createMemoryRepo({ ...config, bots: [...config.bots, other] });
  189. const readState = repo.readState;
  190. // 模拟真实 JSON reader 的独立快照,不能让共享对象引用掩盖丢更新。
  191. repo.readState = async () => structuredClone(await readState());
  192. const service = f.createBotsService({
  193. repo: repo as never,
  194. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  195. runStartupBackgroundTasks: false,
  196. });
  197. try {
  198. const replies = await Promise.all(
  199. ["webhook-1", "webhook-2"].map((botId, index) =>
  200. service.handleInboundMessage({
  201. botId,
  202. actor: { ...actor, botId, providerUserId: `user-${index + 1}` },
  203. text: "/status",
  204. }),
  205. ),
  206. );
  207. expect(replies.every((reply) => reply[0]?.text?.includes("工作区"))).toBe(true);
  208. expect(Object.keys((await repo.readState()).bots).sort()).toEqual(["webhook-1", "webhook-2"]);
  209. } finally {
  210. service.disposeAll();
  211. }
  212. });
  213. it("旧远端 canonical 通过入口交接到稳定持库 host,保留执行 identity", async () => {
  214. const fixture = f.createBotProjectServices();
  215. const readDirectory = fixture.remoteProjectService.readDirectory;
  216. const legacyIdentity = "remote:ssh:old:22:user:/tmp/workspace";
  217. const repo = f.createMemoryRepo(config, {
  218. version: 3,
  219. bots: {
  220. "webhook-1": {
  221. botId: "webhook-1",
  222. workspacePath: "/tmp/workspace",
  223. workspaceIdentity: legacyIdentity,
  224. mode: "draft",
  225. activeTaskId: null,
  226. updatedAt: 1,
  227. },
  228. },
  229. });
  230. const service = f.createBotsService({
  231. ...fixture,
  232. repo: repo as never,
  233. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  234. remoteProjectService: {
  235. readDirectory: async () => {
  236. const directory = await readDirectory();
  237. return {
  238. ...directory,
  239. entries: directory.entries.map((entry) => ({
  240. ...entry,
  241. legacyWorkspace: {
  242. kind: "remote" as const,
  243. workspacePath: "/tmp/workspace",
  244. workspaceIdentity: legacyIdentity,
  245. target: { kind: "ssh" as const, host: "old", port: 22, username: "user" },
  246. lastOpenedAt: 1,
  247. },
  248. })),
  249. };
  250. },
  251. },
  252. });
  253. try {
  254. await service.handleInboundMessage({ botId: "webhook-1", actor, text: "/status" });
  255. expect((await repo.readState()).bots["webhook-1"]).toMatchObject({
  256. hostId: "remote:server:test-owner",
  257. projectId: "project-0",
  258. workspaceIdentity: legacyIdentity,
  259. workspacePath: "/tmp/workspace",
  260. additionalDirectories: [],
  261. });
  262. } finally {
  263. service.disposeAll();
  264. }
  265. });
  266. it("远端项目移除重加后不能接受旧 prepareSession 结果", async () => {
  267. const fixture = f.createBotProjectServices();
  268. let generation = "first";
  269. const repo = f.createMemoryRepo(config);
  270. const prepare = fixture.projectService.prepareSession;
  271. const readDirectory = fixture.remoteProjectService.readDirectory;
  272. const service = f.createBotsService({
  273. ...fixture,
  274. repo: repo as never,
  275. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  276. projectService: {
  277. ...fixture.projectService,
  278. prepareSession: async (input) => {
  279. const result = await prepare(input);
  280. generation = "readded";
  281. return result;
  282. },
  283. },
  284. remoteProjectService: {
  285. readDirectory: async () => {
  286. const directory = await readDirectory();
  287. return {
  288. hosts: directory.hosts.map((host) => ({ ...host, membershipId: generation })),
  289. entries: directory.entries.map((entry) => ({ ...entry, id: generation })),
  290. };
  291. },
  292. },
  293. });
  294. try {
  295. await service
  296. .handleInboundMessage({ botId: "webhook-1", actor, text: "/status" })
  297. .catch(() => undefined);
  298. expect((await repo.readState()).bots["webhook-1"]).toBeUndefined();
  299. } finally {
  300. service.disposeAll();
  301. }
  302. });