plugin-extension-host-runtime.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. // PLM-EXT-2A:扩展进程基础设施与插槽(docs/plugins/extension-host.md §6、§12、§15、§16.1、§16.2)。
  2. // 隔离 HOME:fixture 插件复制到 E2E HOME,经 ~/.zcode/cli/config.json 的 plugins.dirs 加载。
  3. // 运行时证据取自 Main 日志([extension-host] 前缀)与 fixture 写出的状态文件。
  4. import { cp, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
  5. import { dirname, join, resolve } from "node:path";
  6. import {
  7. TID_CHAT_CONTEXT_USAGE_TRIGGER,
  8. TID_CHAT_MODEL_SELECT_TRIGGER,
  9. TID_V4_MODEL_CONFIG,
  10. TID_EXTENSION_COMPOSER_STATUS,
  11. TID_SIDE_PANE_EXTENSIONS,
  12. TID_SIDE_PANE_EXTENSIONS_STOPPED,
  13. TID_SIDE_PANE_EXTENSION_PROBLEM,
  14. TID_SIDE_PANE_EXTENSION_VIEW_ITEM,
  15. } from "@zcode/shared/test-ids";
  16. import {
  17. DEFAULT_WORKSPACE,
  18. clearAppData,
  19. getE2EAppDataPaths,
  20. setCurrentElectronRendererContentSize,
  21. } from "#e2e/helpers/desktop-app";
  22. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  23. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  24. import { ensureSidePaneEntryVisible } from "#e2e/helpers/browser-side-pane";
  25. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  26. import {
  27. capturePluginManualReview,
  28. requirePluginManualReview,
  29. setPluginPresentation,
  30. } from "#e2e/helpers/plugin-management-lifecycle";
  31. const CASE_ID = "PLM-EXT-2A";
  32. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  33. const FIXTURE_ROOT = resolve(
  34. process.cwd(),
  35. "test/e2e/fixtures/fs/plugins/plugin-extension-host-runtime",
  36. );
  37. const PLUGINS = ["e2e-ext-status", "e2e-ext-hang", "e2e-ext-invalid", "e2e-ext-incompatible"];
  38. const STATUS_ITEM = "e2e-ext-status@inline/status";
  39. const READY_TEXT = "E2E ok";
  40. const HANG_TEXT = "E2E hang";
  41. const HANG_ITEM = "e2e-ext-hang@inline/hang";
  42. /** 启动页视图条目(静态声明):扩展进程停止后照常显示,标签变为「扩展已停止」,操作改为重新加载。 */
  43. const PANEL_ITEM = "e2e-ext-status@inline/open-panel";
  44. /** 引用未声明视图的条目:只有它不可用,问题行带字段路径。 */
  45. const BROKEN_ITEM_PATH = 'slots["sidePane.launcher"][1].target.view';
  46. /** 只由设置页注入的网络变量(main/extensionHostSupervisor.ts 的 PROXY / NO_PROXY / CA 键)。 */
  47. const SETTINGS_NETWORK_ENV = new Set([
  48. "HTTP_PROXY",
  49. "HTTPS_PROXY",
  50. "http_proxy",
  51. "https_proxy",
  52. "NO_PROXY",
  53. "no_proxy",
  54. "NODE_EXTRA_CA_CERTS",
  55. ]);
  56. /** 与 main/extensionHostSupervisor.ts 的 EXTENSION_HOST_ENV_ALLOWLIST 一致,外加进程标签。 */
  57. const ENV_ALLOWLIST = new Set([
  58. "PATH",
  59. "HOME",
  60. "USERPROFILE",
  61. "TMPDIR",
  62. "TEMP",
  63. "TMP",
  64. "LANG",
  65. "LC_ALL",
  66. "LC_CTYPE",
  67. "SystemRoot",
  68. "windir",
  69. "APPDATA",
  70. "LOCALAPPDATA",
  71. "NODE_ENV",
  72. "ZCODE_PROCESS_LABEL",
  73. ]);
  74. /**
  75. * 系统在子进程启动时注入的键,不来自 Window Host 的环境(见 docs/plugins/extension-host.md §12.1):
  76. * macOS 上 Chromium 的子进程启动器写 MACH_PORT_RENDEZVOUS_PEER_VALDATION,CoreFoundation 写 __CF_USER_TEXT_ENCODING。
  77. */
  78. const PLATFORM_INJECTED_ENV = new Set([
  79. "MACH_PORT_RENDEZVOUS_PEER_VALDATION",
  80. "__CF_USER_TEXT_ENCODING",
  81. ]);
  82. const evidence: Record<string, unknown> = {};
  83. /** 只在这一行之后找日志:种子前的首次启动也有一个(没有插件的)扩展进程。 */
  84. let logCursor = 0;
  85. function fixtureHome(): string {
  86. return join(getE2EAppDataPaths().homeDir, "fixtures", "extension-host");
  87. }
  88. async function seedExtensionFixtures(): Promise<void> {
  89. const target = fixtureHome();
  90. await mkdir(target, { recursive: true });
  91. for (const name of PLUGINS) {
  92. await cp(join(FIXTURE_ROOT, name), join(target, name), { recursive: true, force: true });
  93. }
  94. const configPath = join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "config.json");
  95. const config = JSON.parse(await readFile(configPath, "utf8").catch(() => "{}")) as Record<
  96. string,
  97. unknown
  98. >;
  99. const plugins = (config.plugins ?? {}) as Record<string, unknown>;
  100. await mkdir(dirname(configPath), { recursive: true });
  101. await writeFile(
  102. configPath,
  103. JSON.stringify(
  104. {
  105. ...config,
  106. plugins: {
  107. ...plugins,
  108. enabled: true,
  109. dirs: PLUGINS.map((name) => join(target, name)),
  110. enabledPlugins: {
  111. ...((plugins.enabledPlugins ?? {}) as Record<string, boolean>),
  112. ...Object.fromEntries(PLUGINS.map((name) => [`${name}@inline`, true])),
  113. },
  114. },
  115. },
  116. null,
  117. 2,
  118. ),
  119. );
  120. }
  121. async function readMainLog(): Promise<string[]> {
  122. const logDir =
  123. process.env.ZCODE_E2E_RUNTIME_LOG_DIR?.trim() || join(resolveE2EStorageRoot(), "v2", "logs");
  124. const names = (await readdir(logDir).catch(() => [] as string[]))
  125. .filter((name) => name.endsWith(".log"))
  126. .sort();
  127. const lines: string[] = [];
  128. for (const name of names) {
  129. lines.push(...(await readFile(join(logDir, name), "utf8")).split("\n"));
  130. }
  131. return lines.filter((line) => line.includes("[extension-host]") || line.includes("[extensions]"));
  132. }
  133. async function waitForLog(
  134. predicate: (line: string) => boolean,
  135. message: string,
  136. timeout = 30000,
  137. ): Promise<string> {
  138. let found = "";
  139. await browser.waitUntil(
  140. async () => {
  141. found = (await readMainLog()).slice(logCursor).find(predicate) ?? "";
  142. return Boolean(found);
  143. },
  144. { timeout, interval: 500, timeoutMsg: message },
  145. );
  146. return found;
  147. }
  148. async function readStatusState(): Promise<{ pid: number; envKeys: string[]; activatedAt: number }> {
  149. return JSON.parse(await readFile(join(fixtureHome(), "e2e-ext-status-state.json"), "utf8"));
  150. }
  151. async function readSlotText(itemId: string): Promise<string | null> {
  152. return browser.execute(
  153. (testId, id) =>
  154. document.querySelector<HTMLElement>(`[data-testid="${testId}"][data-extension-item="${id}"]`)
  155. ?.textContent ?? null,
  156. TID_EXTENSION_COMPOSER_STATUS,
  157. itemId,
  158. );
  159. }
  160. async function waitForSlotText(itemId: string, text: string | null, timeout = 30000) {
  161. await browser.waitUntil(async () => (await readSlotText(itemId)) === text, {
  162. timeout,
  163. interval: 250,
  164. timeoutMsg: `composer.status ${itemId} should be ${text ?? "absent"}`,
  165. });
  166. }
  167. async function clickSlot(itemId: string): Promise<void> {
  168. await browser.execute(
  169. (testId, id) => {
  170. document
  171. .querySelector<HTMLElement>(`[data-testid="${testId}"][data-extension-item="${id}"]`)
  172. ?.click();
  173. },
  174. TID_EXTENSION_COMPOSER_STATUS,
  175. itemId,
  176. );
  177. }
  178. function isAlive(pid: number): boolean {
  179. try {
  180. process.kill(pid, 0);
  181. return true;
  182. } catch {
  183. return false;
  184. }
  185. }
  186. async function waitForGenRunning(gen: number, timeout = 30000): Promise<void> {
  187. await waitForLog(
  188. (line) => line.includes(`[extension-host] gen=${gen} status=running`),
  189. `extension host gen=${gen} should be running`,
  190. timeout,
  191. );
  192. }
  193. /** 打开右侧面板的启动页。窄窗口会收起面板但保留 DOM,所以按「可见」判断,不按「存在」。 */
  194. async function openLauncher(): Promise<void> {
  195. await ensureSidePaneEntryVisible();
  196. await browser.waitUntil(
  197. async () => {
  198. if (await $('[data-side-pane-open-tab-item="browser"]').isDisplayed()) return true;
  199. // 窄屏收起后 DOM 仍存在;按平台发真实快捷键,避免 Windows 收到 macOS 的 Meta 后一直不可见。
  200. await browser.execute(() => {
  201. const mac = navigator.platform.startsWith("Mac");
  202. window.dispatchEvent(
  203. new KeyboardEvent("keydown", {
  204. key: "b",
  205. code: "KeyB",
  206. altKey: true,
  207. metaKey: mac,
  208. ctrlKey: !mac,
  209. bubbles: true,
  210. cancelable: true,
  211. }),
  212. );
  213. });
  214. return false;
  215. },
  216. { timeout: 15000, interval: 1000, timeoutMsg: "side pane launcher should be visible" },
  217. );
  218. }
  219. async function runReloadFromCommandCenter(): Promise<void> {
  220. // 窄屏会保留已收起侧栏的 DOM,直接点击搜索会被正文遮挡;用实际快捷键打开命令中心。
  221. await browser.keys([process.platform === "darwin" ? "Meta" : "Control", "k"]);
  222. const input = $('[role="dialog"] [cmdk-input]');
  223. await input.waitForDisplayed({ timeout: 10000 });
  224. await input.setValue(">重新加载扩展");
  225. await browser.waitUntil(
  226. async () =>
  227. browser.execute(() => {
  228. const item = Array.from(
  229. document.querySelectorAll<HTMLElement>('[role="dialog"] [cmdk-item]'),
  230. ).find((element) => /重新加载扩展|Reload extensions/.test(element.textContent ?? ""));
  231. if (!item) return false;
  232. item.click();
  233. return true;
  234. }),
  235. { timeout: 10000, timeoutMsg: "command center should list 重新加载扩展" },
  236. );
  237. }
  238. interface LauncherRow {
  239. item: string | undefined;
  240. text: string | null;
  241. title: string | null;
  242. }
  243. /** 启动页「扩展」分区的某一类行(问题行或视图条目)。 */
  244. async function readLauncherRows(testId: string): Promise<LauncherRow[]> {
  245. return browser.execute(
  246. (rowTestId) =>
  247. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid="${rowTestId}"]`)).map(
  248. (row) => ({
  249. item: row.dataset.sidePaneOpenTabItem,
  250. text: row.textContent,
  251. title: row.getAttribute("title"),
  252. }),
  253. ),
  254. testId,
  255. );
  256. }
  257. function findRow(rows: LauncherRow[], item: string): LauncherRow | undefined {
  258. return rows.find((row) => row.item === item);
  259. }
  260. describe("PLM-EXT-2A 扩展进程基础设施与插槽", () => {
  261. after(async () => {
  262. await writeFile(
  263. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-2a-evidence.json"),
  264. JSON.stringify(evidence, null, 2),
  265. ).catch(() => undefined);
  266. await clearAppData();
  267. });
  268. it("插槽、问题行、崩溃恢复、卡死预算、重新加载、环境变量与退出收口", async function () {
  269. this.timeout(420000);
  270. requirePluginManualReview();
  271. await seedExtensionFixtures();
  272. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  273. afterElectronProcessExit: async () => {
  274. logCursor = (await readMainLog()).length;
  275. },
  276. });
  277. // 配好上游模型并进入真实草稿:草稿有预热会话,composer.status 的点击作用域是会话。
  278. await prepareV4ConversationE2E();
  279. await setCurrentElectronRendererContentSize(1400, 900);
  280. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  281. // (a) 激活后 composer.status 显示在用量圆环左边。
  282. await waitForSlotText(STATUS_ITEM, READY_TEXT, 60000);
  283. // 草稿没有用量数据时圆环不渲染;插槽紧挨模型控件组(圆环、模型选择器)之前。
  284. const layout = await browser.execute(
  285. (slotTestId, ringTestId, configTestId, modelTestId, id) => {
  286. const slot = document.querySelector<HTMLElement>(
  287. `[data-testid="${slotTestId}"][data-extension-item="${id}"]`,
  288. );
  289. const ring = document.querySelector<HTMLElement>(`[data-testid="${ringTestId}"]`);
  290. const model = document.querySelector<HTMLElement>(`[data-testid="${modelTestId}"]`);
  291. let next = slot?.nextElementSibling ?? null;
  292. while (next && next.getAttribute("data-testid") === slotTestId) {
  293. next = next.nextElementSibling;
  294. }
  295. return {
  296. beforeModelControls: next?.getAttribute("data-testid") === configTestId,
  297. ringPresent: Boolean(ring),
  298. slotRight: slot?.getBoundingClientRect().right ?? null,
  299. ringLeft: ring?.getBoundingClientRect().left ?? null,
  300. modelLeft: model?.getBoundingClientRect().left ?? null,
  301. ringFollowsSlot: ring
  302. ? Boolean(slot && slot.compareDocumentPosition(ring) & Node.DOCUMENT_POSITION_FOLLOWING)
  303. : null,
  304. };
  305. },
  306. TID_EXTENSION_COMPOSER_STATUS,
  307. TID_CHAT_CONTEXT_USAGE_TRIGGER,
  308. TID_V4_MODEL_CONFIG,
  309. TID_CHAT_MODEL_SELECT_TRIGGER,
  310. STATUS_ITEM,
  311. );
  312. evidence.layout = layout;
  313. expect(layout.beforeModelControls).toBe(true);
  314. if (layout.ringPresent) expect(layout.ringFollowsSlot).toBe(true);
  315. for (const right of [layout.ringLeft, layout.modelLeft]) {
  316. if (layout.slotRight !== null && right !== null) {
  317. expect(layout.slotRight).toBeLessThanOrEqual(right + 1);
  318. }
  319. }
  320. await waitForLog(
  321. (line) => line.includes("[e2e-ext-status@inline] activated in"),
  322. "activation log",
  323. );
  324. await waitForLog(
  325. (line) => /\[extension-host\] gen=1 contributions snapshot gen=1 rev=\d+/.test(line),
  326. "contributions snapshot log",
  327. );
  328. await waitForLog(
  329. (line) => line.includes("[extensions]") && line.includes("contributions snapshot gen=1"),
  330. "window host snapshot relay log",
  331. );
  332. // 静态声明归 Window Host(§16.1):它读清单生成静态表,只把合法、兼容的扩展声明交给扩展进程。
  333. // 静态表包含插件清单里的每个插件(隔离 HOME 里还有不带 extension 的内置插件),扩展只有 2 个合法兼容。
  334. const staticTableLine = await waitForLog(
  335. (line) =>
  336. line.includes("[extensions]") &&
  337. /static table rev=\d+ plugins=\d+ extensions=2 /.test(line),
  338. "the window host should build the static table from every inventory plugin",
  339. );
  340. evidence.staticTableLog = staticTableLine;
  341. expect(Number(/plugins=(\d+)/.exec(staticTableLine)?.[1])).toBeGreaterThanOrEqual(
  342. PLUGINS.length,
  343. );
  344. evidence.declarationsLog = await waitForLog(
  345. (line) =>
  346. line.includes("[extensions]") && line.includes("declarations pushed gen=1 extensions=2"),
  347. "the window host should push only valid, compatible extensions",
  348. );
  349. // 未知插槽 id 只记诊断;引用未声明视图的条目只让它自己不可用(不交给扩展进程)。
  350. evidence.ignoredSlotLog = await waitForLog(
  351. (line) =>
  352. line.includes("manifest ignored e2e-ext-status@inline") &&
  353. line.includes('slots["future.slot"]'),
  354. "an unknown slot id should be ignored with a diagnostic",
  355. );
  356. evidence.unusableItemLog = await waitForLog(
  357. (line) => line.includes("E2E_EXT_UNUSABLE_ITEM not-declared"),
  358. "the unusable item should not reach the extension host",
  359. );
  360. // 点击执行命令:作用域为当前会话(草稿为预热会话),扩展按该会话写入文字。
  361. await clickSlot(STATUS_ITEM);
  362. await waitForSlotText(STATUS_ITEM, "E2E #1");
  363. evidence.commandLog = await waitForLog(
  364. (line) => line.includes("E2E_EXT_COMMAND_RUN") && line.includes("clicks=1"),
  365. "command run log",
  366. );
  367. expect(evidence.commandLog).toContain("scope=session");
  368. // 运行时护栏:ctx 冻结、process.exit 被拦截、未声明 id 抛 not-declared、未捕获错误归因插件。
  369. const guardLines = (await readMainLog()).slice(logCursor);
  370. evidence.guards = guardLines.filter((line) =>
  371. /E2E_EXT_(CTX_FROZEN|EXIT_BLOCKED|NOT_DECLARED)|E2E_EXT_UNCAUGHT/.test(line),
  372. );
  373. expect(guardLines.some((line) => line.includes("E2E_EXT_CTX_FROZEN true"))).toBe(true);
  374. expect(guardLines.some((line) => line.includes("E2E_EXT_EXIT_BLOCKED internal"))).toBe(true);
  375. expect(guardLines.some((line) => line.includes("E2E_EXT_NOT_DECLARED not-declared"))).toBe(
  376. true,
  377. );
  378. await waitForLog(
  379. (line) =>
  380. line.includes("[e2e-ext-status@inline] uncaught exception") &&
  381. line.includes("E2E_EXT_UNCAUGHT"),
  382. "uncaught error should be logged with the plugin id",
  383. );
  384. // (e) 环境变量只有白名单里的键,外加设置页注入的网络变量。代理、No Proxy 与 CA 不在白名单里,只来自
  385. // 设置页(与 CLI 相同):capture 模式下 WDIO 把自己的代理与 CA 写进隔离 HOME 的 setting.json,所以这里
  386. // 可能出现。「设置页留空时一个都没有」由 PLM-EXT-H3(plugin-extension-network)断言。
  387. const envLine = await waitForLog((line) => line.includes("E2E_EXT_ENV_KEYS"), "env keys log");
  388. const envKeys = JSON.parse(
  389. envLine.slice(envLine.indexOf("[", envLine.indexOf("E2E_EXT_ENV_KEYS"))),
  390. ) as string[];
  391. evidence.envKeys = envKeys;
  392. const unexpected = envKeys.filter(
  393. (key) =>
  394. !ENV_ALLOWLIST.has(key) &&
  395. !PLATFORM_INJECTED_ENV.has(key) &&
  396. !SETTINGS_NETWORK_ENV.has(key),
  397. );
  398. evidence.envNotAllowlisted = envKeys.filter((key) => !ENV_ALLOWLIST.has(key));
  399. expect(unexpected).toEqual([]);
  400. expect(envKeys.some((key) => /OTEL|TELEMETRY|OAUTH|SECRET|TOKEN|BIGMODEL/i.test(key))).toBe(
  401. false,
  402. );
  403. expect(envKeys).toContain("ZCODE_PROCESS_LABEL");
  404. // (d) 启动页「扩展」分区:清单非法(悬停带字段路径)、版本不兼容、条目不可用。
  405. await openLauncher();
  406. await $(`[data-testid="${TID_SIDE_PANE_EXTENSIONS}"]`).waitForExist({ timeout: 15000 });
  407. const assertProblemRows = (problems: LauncherRow[]) => {
  408. const invalid = findRow(problems, "extension-problem:e2e-ext-invalid@inline");
  409. const incompatible = findRow(problems, "extension-problem:e2e-ext-incompatible@inline");
  410. const unusableItem = findRow(problems, "extension-problem:e2e-ext-status@inline");
  411. expect(invalid?.text).toContain("清单非法");
  412. expect(invalid?.title).toContain("extension.contributes.commands[0].titel");
  413. expect(incompatible?.text).toContain("版本不兼容");
  414. expect(incompatible?.title).toContain("^2.0.0");
  415. // 条目不可用只影响它自己:同一插件的 composer.status 与启动页条目照常。
  416. expect(unusableItem?.text).toContain("清单非法");
  417. expect(unusableItem?.title).toContain(BROKEN_ITEM_PATH);
  418. };
  419. const problems = await readLauncherRows(TID_SIDE_PANE_EXTENSION_PROBLEM);
  420. evidence.problems = problems;
  421. assertProblemRows(problems);
  422. // 静态条目:扩展进程运行时是普通的「打开」行。
  423. const panelRunning = findRow(
  424. await readLauncherRows(TID_SIDE_PANE_EXTENSION_VIEW_ITEM),
  425. `extension-view:${PANEL_ITEM}`,
  426. );
  427. evidence.panelRowRunning = panelRunning;
  428. expect(panelRunning?.text).toContain("E2E 状态面板");
  429. expect(panelRunning?.text).not.toContain("扩展已停止");
  430. // (g) 深浅主题、中英文截图:插槽与启动页分区(分区在启动页底部,先滚到可见)。
  431. await browser.execute((testId) => {
  432. document.querySelector(`[data-testid="${testId}"]`)?.scrollIntoView({ block: "center" });
  433. }, TID_SIDE_PANE_EXTENSIONS);
  434. const screenshots: string[] = [];
  435. for (const [locale, theme] of [
  436. ["zh-CN", "zai-light"],
  437. ["zh-CN", "zai-dark"],
  438. ["en-US", "zai-light"],
  439. ["en-US", "zai-dark"],
  440. ] as const) {
  441. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  442. screenshots.push(await capturePluginManualReview(CASE_ID, `slots-${locale}-${theme}`));
  443. }
  444. evidence.screenshots = screenshots;
  445. // 工具栏变窄时扩展条目最先收起(只留图标):任何其他档位收起时,扩展条目必须已收起。
  446. // 900px 在部分 Windows 环境下仍能容纳完整工具栏;使用更窄视口建立溢出的前提,保留收起断言。
  447. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 500, height: 900 });
  448. await browser.waitUntil(
  449. async () =>
  450. browser.execute(
  451. (testId) =>
  452. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid="${testId}"]`)).every(
  453. (element) => element.dataset.composerCompact === "true",
  454. ),
  455. TID_EXTENSION_COMPOSER_STATUS,
  456. ),
  457. { timeout: 10000, timeoutMsg: "extension items should collapse first in a narrow toolbar" },
  458. );
  459. const collapse = await browser.execute(() =>
  460. Array.from(document.querySelectorAll<HTMLElement>("[data-composer-collapse-priority]")).map(
  461. (element) => ({
  462. priority: element.dataset.composerCollapsePriority,
  463. compact: element.dataset.composerCompact ?? null,
  464. }),
  465. ),
  466. );
  467. evidence.narrowCollapse = collapse;
  468. screenshots.push(await capturePluginManualReview(CASE_ID, "composer-narrow-zh-CN-zai-light"));
  469. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  470. // (b) 杀掉扩展进程:gen + 1 重启,插槽文字由扩展重新设置(动态值随进程清空)。
  471. const first = await readStatusState();
  472. evidence.gen1Pid = first.pid;
  473. process.kill(first.pid, "SIGKILL");
  474. await waitForLog(
  475. (line) =>
  476. line.includes("[extension-host] gen=1 extension host exited") &&
  477. line.includes("intent=crash"),
  478. "gen=1 exit should be logged as a crash",
  479. );
  480. await waitForGenRunning(2);
  481. await browser.waitUntil(async () => (await readStatusState()).pid !== first.pid, {
  482. timeout: 30000,
  483. timeoutMsg: "extension should activate again in the new process",
  484. });
  485. await waitForSlotText(STATUS_ITEM, READY_TEXT);
  486. // (c) 卡死:死循环命令 15 秒左右被判卡死并重启(计入预算)。
  487. const hangStartedAt = Date.now();
  488. await waitForSlotText(HANG_ITEM, HANG_TEXT);
  489. await clickSlot(HANG_ITEM);
  490. await waitForLog(
  491. (line) => line.includes("[extension-host] gen=2 unresponsive"),
  492. "busy loop should be detected",
  493. 30000,
  494. );
  495. evidence.hangDetectedMs = Date.now() - hangStartedAt;
  496. expect(evidence.hangDetectedMs as number).toBeLessThan(25000);
  497. await waitForGenRunning(3);
  498. await waitForSlotText(HANG_ITEM, HANG_TEXT);
  499. // 第 3 次崩溃:最后一次自动重启,退避 4s。
  500. await clickSlot(HANG_ITEM);
  501. await waitForLog(
  502. (line) => line.includes("[extension-host] gen=3 restarting in 4000ms (restart 3/3)"),
  503. "the third crash should use the last backoff step",
  504. 30000,
  505. );
  506. await waitForGenRunning(4);
  507. await waitForSlotText(HANG_ITEM, HANG_TEXT);
  508. // 第 4 次崩溃:5 分钟内超过 3 次自动重启,预算耗尽,扩展进程停止。
  509. await clickSlot(HANG_ITEM);
  510. await waitForLog(
  511. (line) => line.includes("[extension-host] gen=4 status=stopped"),
  512. "crash budget should be exhausted",
  513. 30000,
  514. );
  515. await waitForSlotText(STATUS_ITEM, null);
  516. await openLauncher();
  517. await $(`[data-testid="${TID_SIDE_PANE_EXTENSIONS_STOPPED}"]`).waitForExist({ timeout: 15000 });
  518. evidence.stoppedRow = await browser.execute(
  519. (testId) => document.querySelector(`[data-testid="${testId}"]`)?.textContent ?? "",
  520. TID_SIDE_PANE_EXTENSIONS_STOPPED,
  521. );
  522. expect(evidence.stoppedRow).toContain("扩展已停止");
  523. expect(await $(`[data-testid="${TID_SIDE_PANE_EXTENSIONS_STOPPED}"]`).isDisplayed()).toBe(true);
  524. // 扩展进程停止后静态声明照常(§16.1):问题行都在;扩展目标的条目照常显示但不可用,
  525. // 标签为「扩展已停止」,操作改为「重新加载」。
  526. const stoppedProblems = await readLauncherRows(TID_SIDE_PANE_EXTENSION_PROBLEM);
  527. evidence.problemsWhileStopped = stoppedProblems;
  528. assertProblemRows(stoppedProblems);
  529. const panelStopped = findRow(
  530. await readLauncherRows(TID_SIDE_PANE_EXTENSION_VIEW_ITEM),
  531. `extension-view:${PANEL_ITEM}`,
  532. );
  533. evidence.panelRowStopped = panelStopped;
  534. expect(panelStopped?.text).toContain("E2E 状态面板");
  535. expect(panelStopped?.text).toContain("扩展已停止");
  536. expect(panelStopped?.text).toContain("重新加载");
  537. await browser.execute((testId) => {
  538. document.querySelector(`[data-testid="${testId}"]`)?.scrollIntoView({ block: "center" });
  539. }, TID_SIDE_PANE_EXTENSIONS_STOPPED);
  540. for (const [locale, theme] of [
  541. ["zh-CN", "zai-light"],
  542. ["en-US", "zai-dark"],
  543. ] as const) {
  544. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  545. screenshots.push(await capturePluginManualReview(CASE_ID, `stopped-${locale}-${theme}`));
  546. }
  547. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  548. // 命令中心「重新加载扩展」:清零预算并重启,已停止时也能用。
  549. await runReloadFromCommandCenter();
  550. await waitForLog(
  551. (line) => line.includes("reload requested; crash budget reset"),
  552. "reload should reach the supervisor",
  553. );
  554. await waitForGenRunning(5);
  555. await waitForSlotText(STATUS_ITEM, READY_TEXT);
  556. await $(`[data-testid="${TID_SIDE_PANE_EXTENSIONS_STOPPED}"]`).waitForExist({
  557. reverse: true,
  558. timeout: 15000,
  559. });
  560. // 重新加载会重读静态表;扩展进程恢复后条目回到「打开」。
  561. await waitForLog(
  562. (line) => line.includes("[extensions]") && /static table rev=\d+ .*\(reload\)/.test(line),
  563. "reload should re-read the static table",
  564. );
  565. const panelReloaded = findRow(
  566. await readLauncherRows(TID_SIDE_PANE_EXTENSION_VIEW_ITEM),
  567. `extension-view:${PANEL_ITEM}`,
  568. );
  569. evidence.panelRowReloaded = panelReloaded;
  570. expect(panelReloaded?.text).not.toContain("扩展已停止");
  571. // (f) 退出 App:扩展进程在退出收口内结束,没有残留进程。
  572. const last = await readStatusState();
  573. evidence.gen5Pid = last.pid;
  574. let aliveAfterQuit: boolean | null = null;
  575. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  576. afterElectronProcessExit: () => {
  577. aliveAfterQuit = isAlive(last.pid);
  578. },
  579. });
  580. evidence.aliveAfterQuit = aliveAfterQuit;
  581. expect(aliveAfterQuit).toBe(false);
  582. evidence.disposeLog = await waitForLog(
  583. (line) =>
  584. line.includes("[extension-host] gen=5 extension host exited") &&
  585. line.includes("intent=dispose"),
  586. "gen=5 should exit through the quit barrier",
  587. );
  588. evidence.lifecycle = (await readMainLog())
  589. .slice(logCursor)
  590. .filter((line) =>
  591. /status=|forked|paired|exited|unresponsive|budget|reload|activated|snapshot|static table|declarations|manifest/.test(
  592. line,
  593. ),
  594. );
  595. });
  596. });