extension-host-views.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /**
  2. * 扩展进程 E2E 的通用操作(docs/plugins/extension-host.md §15):插件目录种子、扩展日志、
  3. * 扩展视图标签页与沙箱页面、composer.status 插槽、侧栏启动页。
  4. *
  5. * 抽取原因:PLM-EXT-2B(fixture 插件)与当时的 PLM-EXT-2C(示例插件 context-inspector,已迁到市场仓库)用同一组读法,
  6. * 两份复制的实现一旦漂移就会出现「一个 spec 绿另一个红」的假信号。
  7. */
  8. import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
  9. import { dirname, join } from "node:path";
  10. import {
  11. TID_EXTENSION_COMPOSER_STATUS,
  12. TID_EXTENSION_VIEW,
  13. TID_SIDE_PANE_EXTENSION_VIEW_ITEM,
  14. } from "@zcode/shared/test-ids";
  15. import { getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  16. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  17. import { ensureSidePaneEntryVisible } from "#e2e/helpers/browser-side-pane";
  18. /** 把插件目录写进隔离 HOME 的 `~/.zcode/cli/config.json`(`plugins.dirs`),并启用为 `<name>@inline`。 */
  19. export async function writePluginDirsConfig(
  20. dirs: readonly string[],
  21. pluginIds: readonly string[],
  22. ): Promise<void> {
  23. const configPath = join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "config.json");
  24. const config = JSON.parse(await readFile(configPath, "utf8").catch(() => "{}")) as Record<
  25. string,
  26. unknown
  27. >;
  28. const plugins = (config.plugins ?? {}) as Record<string, unknown>;
  29. await mkdir(dirname(configPath), { recursive: true });
  30. await writeFile(
  31. configPath,
  32. JSON.stringify(
  33. {
  34. ...config,
  35. plugins: {
  36. ...plugins,
  37. enabled: true,
  38. dirs: [...dirs],
  39. enabledPlugins: {
  40. ...((plugins.enabledPlugins ?? {}) as Record<string, boolean>),
  41. ...Object.fromEntries(pluginIds.map((id) => [id, true])),
  42. },
  43. },
  44. },
  45. null,
  46. 2,
  47. ),
  48. );
  49. }
  50. // —— 日志:Main 以 [extension-host] / [extensions] 等前缀写进 ~/.zcode/v2/logs ——
  51. async function readExtensionLogLines(): Promise<string[]> {
  52. const logDir =
  53. process.env.ZCODE_E2E_RUNTIME_LOG_DIR?.trim() || join(resolveE2EStorageRoot(), "v2", "logs");
  54. const names = (await readdir(logDir).catch(() => [] as string[]))
  55. .filter((name) => name.endsWith(".log"))
  56. .sort();
  57. const lines: string[] = [];
  58. for (const name of names) {
  59. lines.push(...(await readFile(join(logDir, name), "utf8")).split("\n"));
  60. }
  61. return lines.filter(
  62. (line) =>
  63. line.includes("[extension-host]") ||
  64. line.includes("[extensions]") ||
  65. line.includes("[extension-slots]") ||
  66. line.includes("[extension-view]"),
  67. );
  68. }
  69. export interface ExtensionLog {
  70. /** 只看这一刻之后的日志:种子前的首次启动也有一个(没有插件的)扩展进程。 */
  71. mark(): Promise<void>;
  72. lines(): Promise<string[]>;
  73. waitFor(predicate: (line: string) => boolean, message: string, timeout?: number): Promise<string>;
  74. }
  75. export function createExtensionLog(): ExtensionLog {
  76. let cursor = 0;
  77. const lines = async () => (await readExtensionLogLines()).slice(cursor);
  78. return {
  79. async mark() {
  80. cursor = (await readExtensionLogLines()).length;
  81. },
  82. lines,
  83. async waitFor(predicate, message, timeout = 30000) {
  84. let found = "";
  85. await browser.waitUntil(
  86. async () => {
  87. found = (await lines()).find(predicate) ?? "";
  88. return Boolean(found);
  89. },
  90. { timeout, interval: 500, timeoutMsg: message },
  91. );
  92. return found;
  93. },
  94. };
  95. }
  96. // —— 扩展视图标签页与沙箱页面 ——
  97. export interface ViewPane {
  98. phase: string | null;
  99. gen: string | null;
  100. instance: string | null;
  101. sandbox: string | null;
  102. scope: string | null;
  103. displayed: boolean;
  104. }
  105. export async function readViewPane(viewId: string): Promise<ViewPane | null> {
  106. return browser.execute(
  107. (paneTestId, id) => {
  108. const pane = document.querySelector<HTMLElement>(
  109. `[data-testid="${paneTestId}"][data-extension-view-id="${id}"]`,
  110. );
  111. if (!pane) return null;
  112. const rect = pane.getBoundingClientRect();
  113. return {
  114. phase: pane.dataset.extensionViewPhase ?? null,
  115. gen: pane.dataset.extensionViewGen ?? null,
  116. instance: pane.dataset.extensionViewInstance ?? null,
  117. sandbox: pane.dataset.extensionViewSandbox ?? null,
  118. scope: pane.dataset.extensionViewScope ?? null,
  119. displayed: rect.width > 0 && rect.height > 0,
  120. };
  121. },
  122. TID_EXTENSION_VIEW,
  123. viewId,
  124. );
  125. }
  126. /** 等待失败时带上最后一次读数与沙箱各 frame 的状态,便于定位页面没跑起来的原因。 */
  127. export async function waitWithEvidence<T>(
  128. read: () => Promise<T | null>,
  129. predicate: (value: T) => boolean,
  130. message: string,
  131. timeout: number,
  132. interval: number,
  133. sandboxOf?: () => Promise<string | null>,
  134. ): Promise<T> {
  135. let latest: T | null = null;
  136. try {
  137. await browser.waitUntil(
  138. async () => {
  139. latest = await read();
  140. return Boolean(latest !== null && predicate(latest));
  141. },
  142. { timeout, interval },
  143. );
  144. } catch {
  145. const sandboxId = sandboxOf ? await sandboxOf() : null;
  146. const frames = sandboxId ? await dumpSandboxFrames(sandboxId) : null;
  147. throw new Error(`${message}: ${JSON.stringify(latest)} frames=${JSON.stringify(frames)}`);
  148. }
  149. return latest!;
  150. }
  151. async function sandboxWebContentsId(sandboxId: string): Promise<number> {
  152. return browser.execute((id) => {
  153. const webview = Array.from(
  154. document.querySelectorAll<HTMLElement & { getWebContentsId?: () => number }>("webview"),
  155. ).find((element) => (element.getAttribute("src") ?? "").includes(`/instance/${id}/`));
  156. try {
  157. return webview?.getWebContentsId?.() ?? 0;
  158. } catch {
  159. return 0;
  160. }
  161. }, sandboxId);
  162. }
  163. async function dumpSandboxFrames(sandboxId: string): Promise<unknown> {
  164. const webContentsId = await sandboxWebContentsId(sandboxId);
  165. if (!webContentsId) return "no webview";
  166. return browser.electron.execute(async (electron, id) => {
  167. const guest = electron.webContents.fromId(id);
  168. if (!guest || guest.isDestroyed()) return "guest destroyed";
  169. return Promise.all(
  170. guest.mainFrame.framesInSubtree.map(async (frame) => ({
  171. url: frame.url,
  172. state: await frame
  173. .executeJavaScript(
  174. `(async () => ({
  175. ready: document.readyState,
  176. zcode: typeof window.zcode,
  177. text: (document.body?.innerText ?? "").slice(0, 300),
  178. errors: window.__e2eErrors ?? null,
  179. scripts: Array.from(document.scripts).map((script) => script.src || "inline"),
  180. handshake: window.zcode
  181. ? await Promise.race([
  182. window.zcode.ready().then(() => "ready", (error) => "error: " + (error?.message ?? error)),
  183. new Promise((resolve) => setTimeout(() => resolve("pending"), 3000)),
  184. ])
  185. : null,
  186. }))()`,
  187. )
  188. .catch((error: unknown) => String(error)),
  189. })),
  190. );
  191. }, webContentsId);
  192. }
  193. export async function waitForViewPane(
  194. viewId: string,
  195. predicate: (pane: ViewPane) => boolean,
  196. message: string,
  197. timeout = 60000,
  198. ): Promise<ViewPane> {
  199. return waitWithEvidence(
  200. () => readViewPane(viewId),
  201. predicate,
  202. message,
  203. timeout,
  204. 300,
  205. async () => (await readViewPane(viewId))?.sandbox ?? null,
  206. );
  207. }
  208. /** 在沙箱里插件页面(relay shell 内的插件 frame)执行一段表达式,返回其结果。 */
  209. export async function evaluateInViewPage<T>(
  210. sandboxId: string,
  211. expression: string,
  212. ): Promise<T | null> {
  213. const webContentsId = await sandboxWebContentsId(sandboxId);
  214. if (!webContentsId) return null;
  215. return (await browser.electron.execute(
  216. async (electron, id, source) => {
  217. const guest = electron.webContents.fromId(id);
  218. if (!guest || guest.isDestroyed()) return null;
  219. const frame = guest.mainFrame.framesInSubtree.find((candidate) =>
  220. candidate.url.startsWith("zcode-sandbox://plugin-"),
  221. );
  222. if (!frame) return null;
  223. return frame.executeJavaScript(source);
  224. },
  225. webContentsId,
  226. expression,
  227. )) as T | null;
  228. }
  229. export interface ViewPage {
  230. dataset: Record<string, string>;
  231. text: string;
  232. }
  233. export async function readViewPage(sandboxId: string): Promise<ViewPage | null> {
  234. return evaluateInViewPage<ViewPage>(
  235. sandboxId,
  236. `({ dataset: { ...document.body.dataset }, text: document.body.innerText })`,
  237. );
  238. }
  239. export async function waitForViewPage(
  240. viewId: string,
  241. predicate: (page: ViewPage) => boolean,
  242. message: string,
  243. timeout = 60000,
  244. ): Promise<ViewPage> {
  245. return waitWithEvidence(
  246. async () => {
  247. const pane = await readViewPane(viewId);
  248. return pane?.sandbox ? readViewPage(pane.sandbox) : null;
  249. },
  250. predicate,
  251. message,
  252. timeout,
  253. 500,
  254. async () => (await readViewPane(viewId))?.sandbox ?? null,
  255. );
  256. }
  257. // —— composer.status 插槽 ——
  258. export interface SlotReading {
  259. text: string;
  260. label: string;
  261. }
  262. export async function readSlot(itemId: string): Promise<SlotReading | null> {
  263. return browser.execute(
  264. (slotTestId, id) => {
  265. const element = document.querySelector<HTMLElement>(
  266. `[data-testid="${slotTestId}"][data-extension-item="${id}"]`,
  267. );
  268. return element
  269. ? { text: element.textContent ?? "", label: element.getAttribute("aria-label") ?? "" }
  270. : null;
  271. },
  272. TID_EXTENSION_COMPOSER_STATUS,
  273. itemId,
  274. );
  275. }
  276. export async function waitForSlot(
  277. itemId: string,
  278. predicate: (slot: SlotReading) => boolean,
  279. message: string,
  280. timeout = 60000,
  281. ): Promise<SlotReading> {
  282. return waitWithEvidence(() => readSlot(itemId), predicate, message, timeout, 200);
  283. }
  284. export async function clickSlot(itemId: string): Promise<void> {
  285. await browser.execute(
  286. (slotTestId, id) => {
  287. document
  288. .querySelector<HTMLElement>(`[data-testid="${slotTestId}"][data-extension-item="${id}"]`)
  289. ?.click();
  290. },
  291. TID_EXTENSION_COMPOSER_STATUS,
  292. itemId,
  293. );
  294. }
  295. // —— 侧栏启动页与标签 ——
  296. /** 命令中心执行「重新加载扩展」(与用户的入口相同)。 */
  297. export async function reloadExtensionsFromCommandCenter(): Promise<void> {
  298. await $('[data-testid="sidebar-search-open"]').click();
  299. const input = $('[role="dialog"] [cmdk-input]');
  300. await input.waitForDisplayed({ timeout: 10000 });
  301. await input.setValue(">重新加载扩展");
  302. await browser.waitUntil(
  303. async () =>
  304. browser.execute(() => {
  305. const item = Array.from(
  306. document.querySelectorAll<HTMLElement>('[role="dialog"] [cmdk-item]'),
  307. ).find((element) => /重新加载扩展|Reload extensions/.test(element.textContent ?? ""));
  308. if (!item) return false;
  309. item.click();
  310. return true;
  311. }),
  312. { timeout: 10000, timeoutMsg: "command center should list 重新加载扩展" },
  313. );
  314. }
  315. /** 关掉右侧面板里当前的标签(视图的 onDidClose 随之触发)。 */
  316. export async function closeActiveSidePaneTab(): Promise<void> {
  317. await browser.waitUntil(
  318. async () =>
  319. browser.execute(() => {
  320. const button = document.querySelector<HTMLButtonElement>(
  321. '[data-side-pane-tab-id][data-state="active"] button',
  322. );
  323. if (!button) return false;
  324. button.click();
  325. return true;
  326. }),
  327. { timeout: 10000, interval: 200, timeoutMsg: "the active side pane tab should close" },
  328. );
  329. }
  330. /** 打开侧栏「新标签页」启动页:没有标签时是启动页本身,有标签时点「+」。 */
  331. export async function openLauncher(): Promise<void> {
  332. await ensureSidePaneEntryVisible();
  333. await browser.waitUntil(
  334. async () =>
  335. browser.execute(() => {
  336. const launcherVisible = Array.from(
  337. document.querySelectorAll<HTMLElement>('[data-side-pane-open-tab-item="browser"]'),
  338. ).some((element) => element.getBoundingClientRect().width > 0);
  339. if (launcherVisible) return true;
  340. document.querySelector<HTMLElement>("[data-side-pane-add-trigger]")?.click();
  341. return false;
  342. }),
  343. { timeout: 15000, interval: 500, timeoutMsg: "side pane launcher should be visible" },
  344. );
  345. }
  346. /** 点启动页「扩展」分区里的视图条目(`<pluginId>/<itemId>`)。 */
  347. export async function openLauncherView(itemId: string): Promise<void> {
  348. await openLauncher();
  349. await browser.waitUntil(
  350. async () =>
  351. browser.execute(
  352. (rowTestId, id) => {
  353. const row = document.querySelector<HTMLElement>(
  354. `[data-testid="${rowTestId}"][data-side-pane-open-tab-item="extension-view:${id}"]`,
  355. );
  356. if (!row) return false;
  357. row.scrollIntoView({ block: "center" });
  358. row.click();
  359. return true;
  360. },
  361. TID_SIDE_PANE_EXTENSION_VIEW_ITEM,
  362. itemId,
  363. ),
  364. { timeout: 30000, interval: 500, timeoutMsg: `launcher should list the view item ${itemId}` },
  365. );
  366. }
  367. export async function readActiveSidePaneTab(): Promise<string | null> {
  368. return browser.execute(
  369. () =>
  370. document
  371. .querySelector<HTMLElement>('[data-side-pane-tab-id][data-state="active"]')
  372. ?.getAttribute("data-side-pane-tab-id") ?? null,
  373. );
  374. }