plugin-extension-plugin-project.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // PLM-EXT-P3C2:扩展不指定项目建会话时放进插件项目(docs/plugins/extension-host.md §17.4 实现 P3c-2、§18.1 H7、
  2. // §17.10 第 3 步)。
  3. // 隔离 HOME:
  4. // - 纯 JS fixture 扩展 e2e-ext-projects(test/e2e/fixtures/fs/plugins/plugin-extension-projects/)经 plugins.dirs
  5. // 加载,清单声明 sessions.write;授权记录预先写进隔离 HOME 的 grants.json(授权流程由 PLM-EXT-P3A 覆盖)。
  6. // 它在输入框状态栏有一个命令:每次点击读一次用例写的步骤文件,按顺序执行操作(写 AGENTS.md、并发的一组
  7. // ctx.sessions.* 操作、单个操作),结果写日志。
  8. // - 模型用 replay(plugin-extension-plugin-project.json):首发夹具要求请求体里有 AGENTS.md 的标记。
  9. // 运行时证据:Main 日志(fixture 的 E2E_PROJECTS_*)、Window Host 项目树、侧栏 DOM、截图。
  10. import { cp, mkdir, writeFile } from "node:fs/promises";
  11. import { join, normalize, resolve } from "node:path";
  12. import { ServiceChannels } from "@zcode/shared";
  13. import { EXTENSION_SESSION_CONSENT_REVISION } from "@zcode/shared/extension-host";
  14. import type { ProjectTree, VirtualProject } from "@zcode/services";
  15. import { DEFAULT_WORKSPACE, clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  16. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  17. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  18. import {
  19. clickSlot,
  20. createExtensionLog,
  21. waitForSlot,
  22. writePluginDirsConfig,
  23. } from "#e2e/helpers/extension-host-views";
  24. import { callHandoffHost, installHandoffRpcProbe } from "#e2e/helpers/remote-project-handoff-probe";
  25. import {
  26. prepareV4ConversationE2E,
  27. waitForV4AssistantMessageContaining,
  28. waitForV4Pane,
  29. } from "#e2e/helpers/v4-conversation";
  30. import {
  31. capturePluginManualReview,
  32. requirePluginManualReview,
  33. setPluginPresentation,
  34. } from "#e2e/helpers/plugin-management-lifecycle";
  35. const CASE_ID = "PLM-EXT-P3C2";
  36. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  37. const FIXTURE_ROOT = resolve(
  38. process.cwd(),
  39. "test/e2e/fixtures/fs/plugins/plugin-extension-projects",
  40. );
  41. const PLUGIN = "e2e-ext-projects";
  42. const PLUGIN_ID = `${PLUGIN}@inline`;
  43. const SLOT_ITEM = `${PLUGIN_ID}/run`;
  44. const AGENTS_MARKER = "E2E_P3C2_AGENTS_MARKER_7f3a";
  45. const PROMPTS = {
  46. first: "E2E_P3C2_FIRST: reply with the persona marker.",
  47. second: "E2E_P3C2_SECOND: reply with the second marker.",
  48. later: "E2E_P3C2_LATER: reply with the later marker.",
  49. recreated: "E2E_P3C2_RECREATED: reply with the recreated marker.",
  50. } as const;
  51. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd();
  52. interface CreateResult {
  53. creation?: string;
  54. firstInput?: string;
  55. session?: { sessionId: string; workspacePath: string; project?: { projectId: string } };
  56. }
  57. interface Op {
  58. name: string;
  59. input?: Record<string, unknown>;
  60. ops?: Op[];
  61. }
  62. interface OpResult {
  63. ok?: CreateResult & Record<string, unknown>;
  64. error?: string;
  65. }
  66. const evidence: Record<string, unknown> = {};
  67. const screenshots: string[] = [];
  68. const log = createExtensionLog();
  69. let seq = 0;
  70. function fixturesDir(): string {
  71. return join(getE2EAppDataPaths().homeDir, "fixtures", "extension-projects");
  72. }
  73. function extensionsDataPath(...parts: string[]): string {
  74. return join(resolveE2EStorageRoot(), "v2", "extensions", ...parts);
  75. }
  76. async function seedPlugin(): Promise<void> {
  77. const target = fixturesDir();
  78. await mkdir(target, { recursive: true });
  79. await cp(join(FIXTURE_ROOT, PLUGIN), join(target, PLUGIN), { recursive: true, force: true });
  80. await writePluginDirsConfig([join(target, PLUGIN)], [PLUGIN_ID]);
  81. await mkdir(extensionsDataPath(), { recursive: true });
  82. await writeFile(
  83. extensionsDataPath("grants.json"),
  84. JSON.stringify({
  85. version: 1,
  86. plugins: {
  87. [PLUGIN_ID]: {
  88. grants: ["sessions.write"],
  89. consentedVersion: "1.0.0",
  90. consentedAt: Date.now(),
  91. // 当前的会话档位含义(§17.12):没有这个字段的旧记录要重新确认,迁移由 PLM-EXT-P3E 覆盖。
  92. consentRevision: EXTENSION_SESSION_CONSENT_REVISION,
  93. },
  94. },
  95. }),
  96. );
  97. }
  98. async function waitForLogAfter(
  99. from: number,
  100. predicate: (line: string) => boolean,
  101. message: string,
  102. timeout = 60000,
  103. ): Promise<string> {
  104. let found = "";
  105. await browser.waitUntil(
  106. async () => {
  107. found = (await log.lines()).slice(from).find(predicate) ?? "";
  108. return Boolean(found);
  109. },
  110. { timeout, interval: 300, timeoutMsg: message },
  111. );
  112. return found;
  113. }
  114. /** 写步骤文件,点状态栏命令,等这一步执行完;结果按「序号.并发内序号」返回。 */
  115. async function runStep(label: string, ops: Op[]): Promise<Record<string, OpResult>> {
  116. seq += 1;
  117. const current = seq;
  118. await writeFile(
  119. join(fixturesDir(), "e2e-ext-projects-step.json"),
  120. JSON.stringify({ seq: current, ops }),
  121. );
  122. const from = (await log.lines()).length;
  123. await waitForSlot(SLOT_ITEM, (slot) => slot.text.includes("E2E projects"), "the run slot");
  124. await clickSlot(SLOT_ITEM);
  125. await waitForLogAfter(
  126. from,
  127. (line) => line.includes(`E2E_PROJECTS_DONE seq=${current}`),
  128. `${label}: the extension should finish step ${current}`,
  129. 120000,
  130. );
  131. const results: Record<string, OpResult> = {};
  132. for (const line of (await log.lines()).slice(from)) {
  133. const match = new RegExp(`E2E_PROJECTS_RESULT seq=${current} index=(\\S+) `).exec(line);
  134. if (!match) continue;
  135. const ok = /\bok=(.*)$/.exec(line)?.[1];
  136. const error = /\berror=(\S+)/.exec(line)?.[1];
  137. results[match[1]!] = {
  138. ...(ok !== undefined ? { ok: JSON.parse(ok) as OpResult["ok"] } : {}),
  139. ...(error ? { error } : {}),
  140. };
  141. }
  142. evidence[`step-${current}-${label}`] = results;
  143. return results;
  144. }
  145. async function readTree(): Promise<ProjectTree> {
  146. return callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [{}]);
  147. }
  148. /** 目录含插件 workspace 的未删除项目(与实现的认定规则相同)。 */
  149. function pluginProjects(tree: ProjectTree, workspace: string): VirtualProject[] {
  150. return tree.projects.filter(
  151. (project) =>
  152. !project.deleted && project.roots.some((root) => normalize(root.rootPath) === workspace),
  153. );
  154. }
  155. function createdSession(result: OpResult | undefined, label: string) {
  156. if (!result?.ok) throw new Error(`${label} failed: ${result?.error ?? "no result"}`);
  157. expect(result.ok).toMatchObject({ creation: "created", firstInput: "accepted" });
  158. return result.ok.session!;
  159. }
  160. /** 侧栏里这个项目的一行:可见、名字是插件名。 */
  161. async function waitForSidebarProject(projectId: string, message: string): Promise<string> {
  162. let name = "";
  163. await browser.waitUntil(
  164. async () => {
  165. name = await browser.execute((id) => {
  166. const section = document.querySelector<HTMLElement>(`section[data-project-id="${id}"]`);
  167. return section?.dataset.projectName ?? "";
  168. }, projectId);
  169. return Boolean(name);
  170. },
  171. { timeout: 30000, interval: 300, timeoutMsg: message },
  172. );
  173. return name;
  174. }
  175. /** 用户在侧栏移除项目:悬停行 → 「更多」→「删除」(侧栏项目菜单的真实路径)。 */
  176. async function removeProjectFromSidebar(projectId: string): Promise<void> {
  177. const section = $(`section[data-project-id="${projectId}"]`);
  178. const row = section.$('[data-testid="virtual-project-row"]');
  179. await row.scrollIntoView({ block: "center" });
  180. await row.moveTo();
  181. await section.$('[data-testid="virtual-project-menu"]').click();
  182. await $('[data-testid="virtual-project-delete"]').click();
  183. await section.waitForExist({ reverse: true, timeout: 30000 });
  184. }
  185. describe("PLM-EXT-P3C2 扩展不指定项目建会话时放进插件项目", () => {
  186. after(async () => {
  187. evidence.screenshots = screenshots;
  188. await writeFile(
  189. join(artifacts, "plm-ext-p3c2-evidence.json"),
  190. JSON.stringify(evidence, null, 2),
  191. ).catch(() => undefined);
  192. await clearAppData();
  193. });
  194. it("并发建会话只建一个插件项目,cwd 是插件 workspace,AGENTS.md 进请求;移除后重新创建", async function () {
  195. this.timeout(900000);
  196. requirePluginManualReview();
  197. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  198. await seedPlugin();
  199. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  200. afterElectronProcessExit: async () => {
  201. await log.mark();
  202. },
  203. });
  204. await prepareV4ConversationE2E();
  205. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  206. const activated = await log.waitFor(
  207. (line) => line.includes(`E2E_PROJECTS_ACTIVATED plugin=${PLUGIN_ID}`),
  208. "the project fixture should activate",
  209. 90000,
  210. );
  211. const dataPath = JSON.parse(/dataPath=(".*")$/.exec(activated)![1]!) as string;
  212. const workspace = normalize(join(dataPath, "workspace"));
  213. evidence.dataPath = dataPath;
  214. await installHandoffRpcProbe();
  215. expect(pluginProjects(await readTree(), workspace)).toEqual([]);
  216. // (a) 先在 workspace 写 AGENTS.md,再同时发两个不带项目的 createSession:只建出一个插件项目。
  217. const first = await runStep("concurrent-create", [
  218. { name: "writeAgents", input: { marker: AGENTS_MARKER } },
  219. {
  220. name: "parallel",
  221. ops: [
  222. { name: "createSession", input: { prompt: PROMPTS.first } },
  223. { name: "createSession", input: { prompt: PROMPTS.second } },
  224. ],
  225. },
  226. ]);
  227. expect(first["0.0"]?.ok).toMatchObject({ workspace: join(dataPath, "workspace") });
  228. const sessionA = createdSession(first["1.0"], "the first concurrent create");
  229. const sessionB = createdSession(first["1.1"], "the second concurrent create");
  230. const projectId = sessionA.project!.projectId;
  231. expect(sessionB.project?.projectId).toBe(projectId);
  232. // H7:会话所在目录就是插件 workspace(项目的唯一目录、主要目录)。
  233. expect(normalize(sessionA.workspacePath)).toBe(workspace);
  234. expect(normalize(sessionB.workspacePath)).toBe(workspace);
  235. let tree = await readTree();
  236. const projects = pluginProjects(tree, workspace);
  237. evidence.projectsAfterConcurrentCreate = projects.map(({ id, name, roots }) => ({
  238. id,
  239. name,
  240. roots,
  241. }));
  242. expect(projects).toHaveLength(1);
  243. expect(projects[0]).toMatchObject({ id: projectId, name: PLUGIN });
  244. expect(projects[0]!.roots).toEqual([
  245. expect.objectContaining({ rootPath: workspace, isPrimary: true }),
  246. ]);
  247. for (const id of [sessionA.sessionId, sessionB.sessionId])
  248. expect(tree.tasks.find((task) => task.taskId === id)?.projectId).toBe(projectId);
  249. expect(
  250. await waitForSidebarProject(projectId, "the sidebar should show the plugin project"),
  251. ).toBe(PLUGIN);
  252. // (b) AGENTS.md 进了请求:首发夹具只在请求体带标记时命中,回复才会出现。
  253. const opened = await runStep("open-first", [
  254. { name: "openSession", input: { sessionId: sessionA.sessionId } },
  255. ]);
  256. expect(opened["0.0"]?.ok).toMatchObject({ status: "opened" });
  257. await waitForV4Pane(
  258. (snapshot) => snapshot.sessionId === sessionA.sessionId,
  259. "the desktop should open the first plugin session",
  260. 30000,
  261. );
  262. await waitForV4AssistantMessageContaining("E2E_P3C2_AGENTS_SEEN", 90000);
  263. await waitForSidebarProject(projectId, "the plugin project should stay in the sidebar");
  264. screenshots.push(await capturePluginManualReview(CASE_ID, "plugin-project-zh-CN-zai-light"));
  265. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  266. screenshots.push(await capturePluginManualReview(CASE_ID, "plugin-project-en-US-zai-dark"));
  267. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  268. // (c) 之后再建一个:复用同一个项目。
  269. const later = await runStep("later-create", [
  270. { name: "createSession", input: { prompt: PROMPTS.later } },
  271. ]);
  272. const sessionC = createdSession(later["0.0"], "the later create");
  273. expect(sessionC.project?.projectId).toBe(projectId);
  274. tree = await readTree();
  275. expect(pluginProjects(tree, workspace).map((project) => project.id)).toEqual([projectId]);
  276. // (d) 用户在侧栏移除这个项目;下一次不带项目的 createSession 新建一个插件项目。
  277. await removeProjectFromSidebar(projectId);
  278. tree = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  279. { includeDeleted: true },
  280. ]);
  281. expect(tree.projects.find((project) => project.id === projectId)?.deleted).toBe(true);
  282. const recreated = await runStep("recreate", [
  283. { name: "createSession", input: { prompt: PROMPTS.recreated } },
  284. ]);
  285. const sessionD = createdSession(recreated["0.0"], "the create after removal");
  286. const newProjectId = sessionD.project!.projectId;
  287. expect(newProjectId).not.toBe(projectId);
  288. expect(normalize(sessionD.workspacePath)).toBe(workspace);
  289. tree = await readTree();
  290. const after = pluginProjects(tree, workspace);
  291. evidence.projectsAfterRecreate = after.map(({ id, name }) => ({ id, name }));
  292. expect(after.map((project) => project.id)).toEqual([newProjectId]);
  293. expect(after[0]!.name).toBe(PLUGIN);
  294. expect(
  295. await waitForSidebarProject(newProjectId, "the sidebar should show the new plugin project"),
  296. ).toBe(PLUGIN);
  297. // 日志:建项目各记一次 info(两次新建),不含路径。
  298. const created = (await log.lines()).filter((line) => line.includes("plugin project created"));
  299. evidence.createdLogLines = created;
  300. expect(created).toHaveLength(2);
  301. expect(JSON.stringify(created)).not.toContain(dataPath);
  302. });
  303. });