plugin-extension-entries.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. // PLM-EXT-P2B:插件入口——主导航 nav.primary 与文件查看器 file.viewer(docs/plugins/extension-host.md §16.3–§16.5)。
  2. // 隔离 HOME:两个纯 JS fixture 插件(test/e2e/fixtures/fs/plugins/plugin-extension-entries/)复制到 E2E HOME,
  3. // 经 ~/.zcode/cli/config.json 的 plugins.dirs 加载:
  4. // - e2e-ext-entries(扩展):nav.primary 的 view 条目,file.viewer 为 .E2EVIEW(大写,验证大小写不敏感)打开视图。
  5. // - e2e-mcp-viewer(只有 MCP App):nav.primary 的 surface 条目,file.viewer 为 .e2edoc 打开页面并调 open_document。
  6. // 正式会话用 replay 创建:提示词带 upstream-e2e-ok,命中 plugin-extension-entries.json 的 plugin-extension-entries-1。
  7. // 运行时证据:Main 日志([extension-host] / [extensions] / [extension-slots] / fixture 的 E2E_ENTRY_*)、
  8. // 视图与 MCP App 页面的 DOM、MCP server 写的调用记录。
  9. import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
  10. import { join, resolve } from "node:path";
  11. import { TID_NAV_PRIMARY_ITEM, TID_WORKSPACE_FILE_TREE_ROW, testId } from "@zcode/shared/test-ids";
  12. import { DEFAULT_WORKSPACE, clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  13. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  14. import {
  15. createExtensionLog,
  16. openLauncher,
  17. readActiveSidePaneTab,
  18. waitForViewPage,
  19. waitForViewPane,
  20. writePluginDirsConfig,
  21. } from "#e2e/helpers/extension-host-views";
  22. import { openProjectFileTree } from "#e2e/helpers/project-sidebar";
  23. import {
  24. approveV4Permission,
  25. prepareV4ConversationE2E,
  26. sendV4Prompt,
  27. waitForV4Pane,
  28. } from "#e2e/helpers/v4-conversation";
  29. import {
  30. capturePluginManualReview,
  31. requirePluginManualReview,
  32. setPluginPresentation,
  33. } from "#e2e/helpers/plugin-management-lifecycle";
  34. const CASE_ID = "PLM-EXT-P2B";
  35. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  36. const FIXTURE_ROOT = resolve(
  37. process.cwd(),
  38. "test/e2e/fixtures/fs/plugins/plugin-extension-entries",
  39. );
  40. const PLUGINS = ["e2e-ext-entries", "e2e-mcp-viewer"];
  41. const EXT_PLUGIN = "e2e-ext-entries@inline";
  42. const MCP_PLUGIN = "e2e-mcp-viewer@inline";
  43. const NAV_VIEW_ITEM = `${EXT_PLUGIN}/nav`;
  44. const NAV_SURFACE_ITEM = `${MCP_PLUGIN}/panel`;
  45. const NAV_VIEW = `${EXT_PLUGIN}/nav`;
  46. const FILE_VIEW = `${EXT_PLUGIN}/file`;
  47. const FILE_DIR = "e2e-entries";
  48. const VIEW_FILE = `${FILE_DIR}/notes.e2eview`;
  49. const DOC_FILE = `${FILE_DIR}/report.e2edoc`;
  50. const XLSX_FILE = `${FILE_DIR}/sheet.xlsx`;
  51. const PROMPT = `E2E_EXT_ENTRIES: Reply with exactly "upstream-e2e-ok" and no other text.`;
  52. const evidence: Record<string, unknown> = {};
  53. const log = createExtensionLog();
  54. function fixtureHome(): string {
  55. return join(getE2EAppDataPaths().homeDir, "fixtures", "extension-entries");
  56. }
  57. async function seedFixtures(): Promise<void> {
  58. const target = fixtureHome();
  59. await mkdir(target, { recursive: true });
  60. for (const name of PLUGINS) {
  61. await cp(join(FIXTURE_ROOT, name), join(target, name), { recursive: true, force: true });
  62. }
  63. await writePluginDirsConfig(
  64. PLUGINS.map((name) => join(target, name)),
  65. PLUGINS.map((name) => `${name}@inline`),
  66. );
  67. const dir = join(DEFAULT_WORKSPACE, FILE_DIR);
  68. await mkdir(dir, { recursive: true });
  69. await writeFile(join(DEFAULT_WORKSPACE, VIEW_FILE), "E2E extension viewer file\n");
  70. await writeFile(join(DEFAULT_WORKSPACE, DOC_FILE), "E2E MCP App viewer file\n");
  71. // 内容不是真的 xlsx:只验证路由(官方面板不在 E2E profile 时回退内置预览)。
  72. await writeFile(join(DEFAULT_WORKSPACE, XLSX_FILE), "not a real workbook\n");
  73. }
  74. interface NavItem {
  75. id: string;
  76. target: string;
  77. text: string;
  78. stopped: boolean;
  79. label: string;
  80. /** 导航条目没有选中态:不能带 aria-pressed(「自动化」「插件市场」才有)。 */
  81. pressable: boolean;
  82. }
  83. async function readNavItems(): Promise<NavItem[]> {
  84. return browser.execute(
  85. (itemTestId) =>
  86. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid="${itemTestId}"]`)).map(
  87. (element) => ({
  88. id: element.dataset.extensionItem ?? "",
  89. target: element.dataset.extensionTarget ?? "",
  90. text: element.textContent ?? "",
  91. stopped: element.dataset.extensionHostStopped === "true",
  92. label: element.getAttribute("aria-label") ?? "",
  93. pressable: element.hasAttribute("aria-pressed"),
  94. }),
  95. ),
  96. TID_NAV_PRIMARY_ITEM,
  97. );
  98. }
  99. async function waitForNavItems(
  100. predicate: (items: NavItem[]) => boolean,
  101. message: string,
  102. timeout = 30000,
  103. ): Promise<NavItem[]> {
  104. let items: NavItem[] = [];
  105. await browser.waitUntil(
  106. async () => {
  107. items = await readNavItems();
  108. return predicate(items);
  109. },
  110. { timeout, interval: 300, timeoutMsg: `${message}: ${JSON.stringify(items)}` },
  111. );
  112. return items;
  113. }
  114. /** 截图前把指针移到窗口左上角:文件树入口会让项目行的悬停卡片一直开着,挡住画面。 */
  115. async function capture(label: string): Promise<string> {
  116. await browser.action("pointer").move({ x: 2, y: 2, origin: "viewport" }).perform();
  117. await browser.pause(300);
  118. return capturePluginManualReview(CASE_ID, label);
  119. }
  120. /** 导航条目的期望顺序:按渲染端同一语言的排序规则比较标题,相同时按插件 id(§16.4)。 */
  121. async function expectedNavOrder(items: NavItem[], locale: string): Promise<string[]> {
  122. return browser.execute(
  123. (entries, lang) =>
  124. [...entries]
  125. .sort(
  126. (a, b) =>
  127. a.text.localeCompare(b.text, lang) ||
  128. (a.id.split("/")[0]! < b.id.split("/")[0]! ? -1 : 1),
  129. )
  130. .map((entry) => entry.id),
  131. items.map((item) => ({ id: item.id, text: item.text })),
  132. locale,
  133. );
  134. }
  135. async function clickNavItem(itemId: string): Promise<void> {
  136. const clicked = await browser.execute(
  137. (itemTestId, id) => {
  138. const element = document.querySelector<HTMLElement>(
  139. `[data-testid="${itemTestId}"][data-extension-item="${id}"]`,
  140. );
  141. element?.click();
  142. return Boolean(element);
  143. },
  144. TID_NAV_PRIMARY_ITEM,
  145. itemId,
  146. );
  147. expect(clicked).toBe(true);
  148. }
  149. /** 左侧主导航的「插件市场」按钮是否选中:用来确认导航条目没有切换主视图。 */
  150. async function readMainView(): Promise<{ pluginStore: boolean; automations: boolean }> {
  151. return browser.execute(() => ({
  152. pluginStore:
  153. document
  154. .querySelector('[data-testid="plugin-store-sidebar-open"]')
  155. ?.getAttribute("aria-pressed") === "true",
  156. automations:
  157. document
  158. .querySelector('[data-testid="automations-open"], [data-testid="sidebar-automations-open"]')
  159. ?.getAttribute("aria-pressed") === "true",
  160. }));
  161. }
  162. /** 所有沙箱 guest 里 E2E MCP 面板页面的 body dataset(标签页保活时可能有多份)。 */
  163. async function readMcpPanelPages(): Promise<Array<Record<string, string>>> {
  164. return (await browser.electron.execute(async (electron) => {
  165. const pages: Array<Record<string, string>> = [];
  166. for (const guest of electron.webContents.getAllWebContents()) {
  167. if (guest.isDestroyed() || !guest.getURL().startsWith("zcode-sandbox://")) continue;
  168. for (const frame of guest.mainFrame.framesInSubtree) {
  169. if (!frame.url.startsWith("zcode-sandbox://plugin-")) continue;
  170. const dataset = (await frame
  171. .executeJavaScript(
  172. `document.querySelector("h1")?.textContent === "E2E MCP panel" ? { ...document.body.dataset } : null`,
  173. )
  174. .catch(() => null)) as Record<string, string> | null;
  175. if (dataset) pages.push(dataset);
  176. }
  177. }
  178. return pages;
  179. })) as Array<Record<string, string>>;
  180. }
  181. async function waitForMcpPanelPage(
  182. predicate: (page: Record<string, string>) => boolean,
  183. message: string,
  184. timeout = 60000,
  185. ): Promise<Record<string, string>> {
  186. let pages: Array<Record<string, string>> = [];
  187. let found: Record<string, string> | undefined;
  188. await browser.waitUntil(
  189. async () => {
  190. pages = await readMcpPanelPages();
  191. found = pages.find(predicate);
  192. return Boolean(found);
  193. },
  194. { timeout, interval: 500, timeoutMsg: `${message}: ${JSON.stringify(pages)}` },
  195. );
  196. return found!;
  197. }
  198. async function clickFileTreeRow(relativePath: string): Promise<void> {
  199. const path = join(DEFAULT_WORKSPACE, relativePath);
  200. await browser.waitUntil(
  201. () =>
  202. browser.execute(
  203. (id) => {
  204. const row = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  205. (element) => element.dataset.testid === id && element.getBoundingClientRect().width > 0,
  206. );
  207. row?.scrollIntoView({ block: "center" });
  208. row?.click();
  209. return Boolean(row);
  210. },
  211. testId(TID_WORKSPACE_FILE_TREE_ROW, path),
  212. ),
  213. { timeout: 15000, interval: 300, timeoutMsg: `file tree row not found: ${relativePath}` },
  214. );
  215. }
  216. /** 回到文件管理标签(打开查看器后当前标签换成了查看器)。 */
  217. async function activateFileManagerTab(): Promise<void> {
  218. await browser.waitUntil(
  219. () =>
  220. browser.execute(() => {
  221. const tab = document.querySelector<HTMLElement>('[data-side-pane-tab-id^="file-manager"]');
  222. tab?.click();
  223. return Boolean(tab);
  224. }),
  225. { timeout: 15000, interval: 300, timeoutMsg: "file manager tab should exist" },
  226. );
  227. }
  228. async function readMcpViewerCalls(): Promise<Array<{ tool: string; path: string }>> {
  229. const raw = await readFile(join(fixtureHome(), "e2e-mcp-viewer-calls.jsonl"), "utf8").catch(
  230. () => "",
  231. );
  232. return raw
  233. .split("\n")
  234. .filter(Boolean)
  235. .map((line) => JSON.parse(line) as { tool: string; path: string });
  236. }
  237. /** 等 open_document 到达 MCP server;中途出现权限请求就批准(页面调工具按会话权限规则授权)。 */
  238. async function waitForOpenDocument(path: string): Promise<void> {
  239. const deadline = Date.now() + 60000;
  240. let approvals = 0;
  241. for (;;) {
  242. if ((await readMcpViewerCalls()).some((call) => call.path === path)) break;
  243. if (Date.now() > deadline) throw new Error(`open_document did not reach the server: ${path}`);
  244. const permissionOpen = await browser.execute(() =>
  245. Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some((element) =>
  246. /Permission required|需要权限/.test(element.getAttribute("aria-label") ?? ""),
  247. ),
  248. );
  249. if (permissionOpen) {
  250. await approveV4Permission();
  251. approvals += 1;
  252. }
  253. await browser.pause(500);
  254. }
  255. evidence.openDocumentApprovals = approvals;
  256. }
  257. async function readExtensionHostPid(): Promise<{ pid: number; activatedAt: number }> {
  258. return JSON.parse(await readFile(join(fixtureHome(), "e2e-ext-entries-state.json"), "utf8")) as {
  259. pid: number;
  260. activatedAt: number;
  261. };
  262. }
  263. /** 连续杀掉扩展进程直到崩溃预算耗尽(§12.1:退避 1s、2s、4s,第 4 次崩溃停止)。返回 stopped 日志行。 */
  264. async function stopExtensionHost(): Promise<string> {
  265. const linesBefore = (await log.lines()).length;
  266. for (let crash = 1; crash <= 4; crash += 1) {
  267. const state = await readExtensionHostPid();
  268. process.kill(state.pid, "SIGKILL");
  269. if (crash === 4) break;
  270. await browser.waitUntil(
  271. async () => {
  272. const next = await readExtensionHostPid().catch(() => state);
  273. return next.activatedAt > state.activatedAt;
  274. },
  275. { timeout: 60000, interval: 500, timeoutMsg: `the extension host should restart (${crash})` },
  276. );
  277. }
  278. let stopped = "";
  279. await browser.waitUntil(
  280. async () => {
  281. stopped =
  282. (await log.lines())
  283. .slice(linesBefore)
  284. .find((line) => /\[extension-host\] gen=\d+ status=stopped/.test(line)) ?? "";
  285. return Boolean(stopped);
  286. },
  287. {
  288. timeout: 60000,
  289. interval: 500,
  290. timeoutMsg: "the extension host should stop after the budget",
  291. },
  292. );
  293. return stopped;
  294. }
  295. describe("PLM-EXT-P2B 插件入口:主导航与文件查看器", () => {
  296. after(async () => {
  297. await writeFile(
  298. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-p2b-evidence.json"),
  299. JSON.stringify(evidence, null, 2),
  300. ).catch(() => undefined);
  301. await clearAppData();
  302. });
  303. it("主导航:视图与 MCP App 条目、根草稿与正式会话、扩展进程停止", async function () {
  304. this.timeout(600000);
  305. requirePluginManualReview();
  306. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  307. await seedFixtures();
  308. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  309. afterElectronProcessExit: () => log.mark(),
  310. });
  311. await prepareV4ConversationE2E();
  312. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  313. await log.waitFor(
  314. (line) => line.includes(`[${EXT_PLUGIN}] activated in`),
  315. "the entries extension should activate",
  316. 60000,
  317. );
  318. evidence.staticTable = await log.waitFor(
  319. (line) => line.includes("[extensions]") && /static table rev=\d+ .*items=/.test(line),
  320. "the window host should read the static table",
  321. );
  322. // (a) 两个导航条目都在「插件市场」之后,按标题排序;深浅主题、中英文截图。
  323. const zhItems = await waitForNavItems(
  324. (items) =>
  325. items.some((item) => item.id === NAV_VIEW_ITEM) &&
  326. items.some((item) => item.id === NAV_SURFACE_ITEM),
  327. "nav.primary should list both fixture entries",
  328. );
  329. evidence.navItemsZh = zhItems;
  330. expect(zhItems.find((item) => item.id === NAV_VIEW_ITEM)?.text).toContain("E2E 导航视图");
  331. expect(zhItems.find((item) => item.id === NAV_SURFACE_ITEM)?.text).toContain("E2E MCP 面板");
  332. expect(zhItems.map((item) => item.id)).toEqual(await expectedNavOrder(zhItems, "zh-CN"));
  333. evidence.navAfterPluginStore = await browser.execute((itemTestId) => {
  334. const store = document.querySelector('[data-testid="plugin-store-sidebar-open"]');
  335. const first = document.querySelector(`[data-testid="${itemTestId}"]`);
  336. return Boolean(
  337. store && first && store.compareDocumentPosition(first) & Node.DOCUMENT_POSITION_FOLLOWING,
  338. );
  339. }, TID_NAV_PRIMARY_ITEM);
  340. expect(evidence.navAfterPluginStore).toBe(true);
  341. const screenshots: string[] = [];
  342. for (const [locale, theme] of [
  343. ["zh-CN", "zai-light"],
  344. ["zh-CN", "zai-dark"],
  345. ["en-US", "zai-light"],
  346. ["en-US", "zai-dark"],
  347. ] as const) {
  348. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  349. const items = await waitForNavItems(
  350. (current) =>
  351. locale === "en-US"
  352. ? current.some((item) => item.text.includes("E2E nav view"))
  353. : current.some((item) => item.text.includes("E2E 导航视图")),
  354. `nav.primary titles should follow ${locale}`,
  355. );
  356. evidence[`navItems-${locale}`] = items.map((item) => item.text);
  357. expect(items.map((item) => item.id)).toEqual(await expectedNavOrder(items, locale));
  358. screenshots.push(await capture(`nav-${locale}-${theme}`));
  359. }
  360. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  361. // (b) 导航 → 扩展视图标签;不切换主视图、没有选中态。
  362. await clickNavItem(NAV_VIEW_ITEM);
  363. const navPane = await waitForViewPane(
  364. NAV_VIEW,
  365. (pane) => pane.phase === "running" && pane.displayed,
  366. "the nav view tab should be running",
  367. );
  368. evidence.navViewPane = navPane;
  369. const navPage = await waitForViewPage(
  370. NAV_VIEW,
  371. (page) => page.dataset.ready === "1",
  372. "the nav view page should render",
  373. );
  374. evidence.navViewPage = navPage.dataset;
  375. expect(navPage.dataset.viewId).toBe("nav");
  376. expect(navPage.dataset.inputKind).toBe("");
  377. expect(await readActiveSidePaneTab()).toBe(`extension-view:${NAV_VIEW}`);
  378. expect(await readMainView()).toEqual({ pluginStore: false, automations: false });
  379. evidence.navViewOpenLog = await log.waitFor(
  380. (line) => line.includes("E2E_ENTRY_VIEW_OPEN view=nav") && line.includes("input=null"),
  381. "the nav view instance should open without input",
  382. );
  383. expect((await readNavItems()).every((item) => !item.pressable)).toBe(true);
  384. screenshots.push(await capture("nav-view-zh-CN-zai-light"));
  385. // (c) 导航 → MCP App 页面,根草稿路径:停在插件市场(没有对话窗格的会话)时点击,
  386. // 先进根草稿、回到对话,再在预热会话就绪后打开页面。
  387. await browser.execute(() =>
  388. document.querySelector<HTMLElement>('[data-testid="plugin-store-sidebar-open"]')?.click(),
  389. );
  390. await browser.waitUntil(async () => (await readMainView()).pluginStore, {
  391. timeout: 15000,
  392. timeoutMsg: "the plugin store main view should open",
  393. });
  394. await clickNavItem(NAV_SURFACE_ITEM);
  395. evidence.draftSurfaceLog = await log.waitFor(
  396. (line) =>
  397. line.includes("[extension-slots] open surface") &&
  398. line.includes(NAV_SURFACE_ITEM.split("/")[0]!) &&
  399. line.includes('"path":"draft"'),
  400. "the surface entry should take the root draft path",
  401. );
  402. await browser.waitUntil(async () => !(await readMainView()).pluginStore, {
  403. timeout: 15000,
  404. timeoutMsg: "the root draft path should return to the conversation",
  405. });
  406. await waitForV4Pane((snapshot) => snapshot.sessionId === "draft", "the pane should be a draft");
  407. const draftPage = await waitForMcpPanelPage(
  408. (page) => page.ready === "1",
  409. "the MCP App page should open in the root draft",
  410. );
  411. evidence.draftPanelPage = draftPage;
  412. const draftTab = (await readActiveSidePaneTab()) ?? "";
  413. evidence.draftPanelTab = draftTab;
  414. expect(draftTab.startsWith("plugin-ui:")).toBe(true);
  415. expect(draftTab).toContain(encodeURIComponent(MCP_PLUGIN));
  416. screenshots.push(await capture("nav-surface-draft-zh-CN-zai-light"));
  417. // (d) 导航 → MCP App 页面,正式会话:发送一条 replay 消息后,在焦点窗格的正式会话里打开。
  418. await sendV4Prompt(PROMPT);
  419. const session = await waitForV4Pane(
  420. (snapshot) => Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  421. "the draft should become a session after the first send",
  422. 60000,
  423. );
  424. const sessionId = session.sessionId ?? "";
  425. evidence.sessionId = sessionId;
  426. await openLauncher();
  427. expect((await readActiveSidePaneTab())?.startsWith("plugin-ui:")).toBe(false);
  428. await clickNavItem(NAV_SURFACE_ITEM);
  429. evidence.sessionSurfaceLog = await log.waitFor(
  430. (line) =>
  431. line.includes("[extension-slots] open surface") &&
  432. line.includes('"path":"session"') &&
  433. line.includes(sessionId),
  434. "the surface entry should open in the focused session",
  435. );
  436. await browser.waitUntil(
  437. async () => {
  438. const active = (await readActiveSidePaneTab()) ?? "";
  439. return active.startsWith("plugin-ui:") && active.includes(encodeURIComponent(sessionId));
  440. },
  441. { timeout: 20000, timeoutMsg: "the MCP App tab should belong to the session" },
  442. );
  443. evidence.sessionPanelTab = await readActiveSidePaneTab();
  444. await waitForMcpPanelPage((page) => page.ready === "1", "the session MCP App page should run");
  445. // (h) 扩展进程停止:连续杀掉扩展进程直到预算耗尽。view 条目显示「扩展已停止」与「重新加载」,
  446. // MCP App 条目照常打开页面(P2a 移到这里的断言)。
  447. evidence.stoppedLog = await stopExtensionHost();
  448. const stoppedItems = await waitForNavItems(
  449. (items) => items.some((item) => item.id === NAV_VIEW_ITEM && item.stopped),
  450. "the view entry should show the stopped state",
  451. );
  452. evidence.stoppedNavItems = stoppedItems;
  453. const stoppedView = stoppedItems.find((item) => item.id === NAV_VIEW_ITEM)!;
  454. expect(stoppedView.text).toContain("E2E 导航视图");
  455. expect(stoppedView.text).toContain("已停止");
  456. expect(stoppedView.text).toContain("重新加载");
  457. expect(stoppedView.label).toContain("扩展已停止");
  458. expect(stoppedItems.find((item) => item.id === NAV_SURFACE_ITEM)?.stopped).toBe(false);
  459. for (const [locale, theme] of [
  460. ["zh-CN", "zai-light"],
  461. ["en-US", "zai-dark"],
  462. ] as const) {
  463. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  464. screenshots.push(await capture(`nav-stopped-${locale}-${theme}`));
  465. }
  466. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  467. await openLauncher();
  468. await clickNavItem(NAV_SURFACE_ITEM);
  469. await browser.waitUntil(
  470. async () => ((await readActiveSidePaneTab()) ?? "").startsWith("plugin-ui:"),
  471. { timeout: 20000, timeoutMsg: "the MCP App entry should still open while stopped" },
  472. );
  473. await waitForMcpPanelPage(
  474. (page) => page.ready === "1",
  475. "the MCP App page should still run while the extension host is stopped",
  476. );
  477. evidence.surfaceWhileStoppedTab = await readActiveSidePaneTab();
  478. // 点击停止的 view 条目 = 重新加载:清零预算并重启,条目回到正常状态。
  479. await clickNavItem(NAV_VIEW_ITEM);
  480. evidence.reloadLog = await log.waitFor(
  481. (line) => line.includes("reload requested; crash budget reset"),
  482. "the stopped entry should reload the extension host",
  483. );
  484. await waitForNavItems(
  485. (items) => items.some((item) => item.id === NAV_VIEW_ITEM && !item.stopped),
  486. "the view entry should recover after reload",
  487. 60000,
  488. );
  489. evidence.navScreenshots = screenshots;
  490. });
  491. it("文件查看器:view 与 surface 查看器、.xlsx 路由与扩展进程停止", async function () {
  492. this.timeout(600000);
  493. const screenshots: string[] = [];
  494. // (e) file.viewer 的 view:.e2eview(清单写 .E2EVIEW)→ 扩展视图标签,每个文件一个,view.input 带文件。
  495. await openProjectFileTree(DEFAULT_WORKSPACE);
  496. await clickFileTreeRow(FILE_DIR);
  497. await clickFileTreeRow(VIEW_FILE);
  498. const fileTabId = `extension-view:${FILE_VIEW}:file:${VIEW_FILE}`;
  499. await browser.waitUntil(async () => (await readActiveSidePaneTab()) === fileTabId, {
  500. timeout: 20000,
  501. timeoutMsg: `the file viewer tab should open: ${fileTabId}`,
  502. });
  503. const filePane = await waitForViewPane(
  504. FILE_VIEW,
  505. (pane) => pane.phase === "running" && pane.displayed,
  506. "the file viewer tab should be running",
  507. );
  508. evidence.fileViewPane = filePane;
  509. const filePage = await waitForViewPage(
  510. FILE_VIEW,
  511. (page) => page.dataset.ready === "1",
  512. "the file viewer page should render",
  513. );
  514. evidence.fileViewPage = filePage.dataset;
  515. expect(filePage.dataset.viewId).toBe("file");
  516. expect(filePage.dataset.inputKind).toBe("file");
  517. expect(filePage.dataset.inputPath).toBe(VIEW_FILE);
  518. expect(filePage.dataset.inputWorkspace).toBe(DEFAULT_WORKSPACE);
  519. evidence.fileTabTitle = await browser.execute(
  520. (id) => document.querySelector(`[data-side-pane-tab-id="${id}"]`)?.textContent ?? "",
  521. fileTabId,
  522. );
  523. expect(evidence.fileTabTitle).toContain("notes.e2eview");
  524. evidence.fileViewOpenLog = await log.waitFor(
  525. (line) =>
  526. line.includes("E2E_ENTRY_VIEW_OPEN view=file") && line.includes(`"path":"${VIEW_FILE}"`),
  527. "the file viewer instance should receive view.input",
  528. );
  529. screenshots.push(await capture("file-view-zh-CN-zai-light"));
  530. // (f) file.viewer 的 surface:.e2edoc → MCP App 页面(每个文件一个标签),页面就绪后宿主调 open_document。
  531. await activateFileManagerTab();
  532. await clickFileTreeRow(DOC_FILE);
  533. await waitForOpenDocument(DOC_FILE);
  534. evidence.mcpViewerCalls = await readMcpViewerCalls();
  535. const docPage = await waitForMcpPanelPage(
  536. (page) => page.openedPath === DOC_FILE,
  537. "the MCP App viewer page should receive the open_document result",
  538. );
  539. evidence.docPanelPage = docPage;
  540. const docTab = (await readActiveSidePaneTab()) ?? "";
  541. evidence.docPanelTab = docTab;
  542. expect(docTab.startsWith("plugin-ui:")).toBe(true);
  543. expect(docTab).toContain("report.e2edoc");
  544. screenshots.push(await capture("file-surface-zh-CN-zai-light"));
  545. // (g) .xlsx 仍先走内置的官方路由:官方 spreadsheets 插件接管,插件声明的查看器不接管。
  546. // 修复原因:这条断言最初写成「没有官方插件、走回退」,是因为开发机仓库根目录的本地
  547. // .zcode/config.json 禁用了官方插件,并经项目配置发现进入了 E2E
  548. // (docs/testing/conversation-session-e2e-development-workflow.md「已知问题」)。干净环境里官方插件
  549. // 默认启用,正确行为是官方路由打开 spreadsheets 页面。
  550. await activateFileManagerTab();
  551. const linesBeforeXlsx = (await log.lines()).length;
  552. await clickFileTreeRow(XLSX_FILE);
  553. await browser.waitUntil(
  554. async () => String((await readActiveSidePaneTab()) ?? "").includes("spreadsheets%40zcode"),
  555. { timeout: 30000, timeoutMsg: ".xlsx should open in the official spreadsheets page" },
  556. );
  557. evidence.xlsxActiveTab = await readActiveSidePaneTab();
  558. const xlsxLines = (await log.lines())
  559. .slice(linesBeforeXlsx)
  560. .filter((line) => line.includes("file viewer"));
  561. evidence.xlsxLines = xlsxLines;
  562. expect(String(evidence.xlsxActiveTab).startsWith("plugin-ui:")).toBe(true);
  563. expect(xlsxLines.some((line) => line.includes("file viewer routed"))).toBe(false);
  564. // 扩展进程停止:view 查看器打不开,不参加选择,.e2eview 走内置预览(文件管理标签内)。
  565. evidence.stoppedAgainLog = await stopExtensionHost();
  566. await waitForNavItems(
  567. (items) => items.some((item) => item.id === NAV_VIEW_ITEM && item.stopped),
  568. "the view entry should show the stopped state again",
  569. );
  570. await activateFileManagerTab();
  571. const linesBeforeStoppedView = (await log.lines()).length;
  572. await clickFileTreeRow(VIEW_FILE);
  573. await browser.waitUntil(
  574. async () => String(await readActiveSidePaneTab()).startsWith("file-manager"),
  575. { timeout: 15000, timeoutMsg: "the .e2eview file should stay in the file manager preview" },
  576. );
  577. evidence.viewFileWhileStoppedTab = await readActiveSidePaneTab();
  578. expect(
  579. (await log.lines())
  580. .slice(linesBeforeStoppedView)
  581. .some((line) => line.includes("file viewer routed")),
  582. ).toBe(false);
  583. await clickNavItem(NAV_VIEW_ITEM);
  584. await waitForNavItems(
  585. (items) => items.some((item) => item.id === NAV_VIEW_ITEM && !item.stopped),
  586. "the view entry should recover after the second reload",
  587. 60000,
  588. );
  589. evidence.fileScreenshots = screenshots;
  590. evidence.lifecycle = (await log.lines()).filter((line) =>
  591. /status=|static table|declarations|view prepared|view opened|open surface|file viewer|E2E_ENTRY|office-viewer/.test(
  592. line,
  593. ),
  594. );
  595. });
  596. });