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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. // 与产品 ⌥⌘B 共用真实 workspace shortcut。
  200. await browser.execute(() => {
  201. window.dispatchEvent(
  202. new KeyboardEvent("keydown", {
  203. key: "b",
  204. code: "KeyB",
  205. altKey: true,
  206. metaKey: true,
  207. bubbles: true,
  208. cancelable: true,
  209. }),
  210. );
  211. });
  212. return false;
  213. },
  214. { timeout: 15000, interval: 1000, timeoutMsg: "side pane launcher should be visible" },
  215. );
  216. }
  217. async function runReloadFromCommandCenter(): Promise<void> {
  218. await $('[data-testid="sidebar-search-open"]').click();
  219. const input = $('[role="dialog"] [cmdk-input]');
  220. await input.waitForDisplayed({ timeout: 10000 });
  221. await input.setValue(">重新加载扩展");
  222. await browser.waitUntil(
  223. async () =>
  224. browser.execute(() => {
  225. const item = Array.from(
  226. document.querySelectorAll<HTMLElement>('[role="dialog"] [cmdk-item]'),
  227. ).find((element) => /重新加载扩展|Reload extensions/.test(element.textContent ?? ""));
  228. if (!item) return false;
  229. item.click();
  230. return true;
  231. }),
  232. { timeout: 10000, timeoutMsg: "command center should list 重新加载扩展" },
  233. );
  234. }
  235. interface LauncherRow {
  236. item: string | undefined;
  237. text: string | null;
  238. title: string | null;
  239. }
  240. /** 启动页「扩展」分区的某一类行(问题行或视图条目)。 */
  241. async function readLauncherRows(testId: string): Promise<LauncherRow[]> {
  242. return browser.execute(
  243. (rowTestId) =>
  244. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid="${rowTestId}"]`)).map(
  245. (row) => ({
  246. item: row.dataset.sidePaneOpenTabItem,
  247. text: row.textContent,
  248. title: row.getAttribute("title"),
  249. }),
  250. ),
  251. testId,
  252. );
  253. }
  254. function findRow(rows: LauncherRow[], item: string): LauncherRow | undefined {
  255. return rows.find((row) => row.item === item);
  256. }
  257. describe("PLM-EXT-2A 扩展进程基础设施与插槽", () => {
  258. after(async () => {
  259. await writeFile(
  260. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-2a-evidence.json"),
  261. JSON.stringify(evidence, null, 2),
  262. ).catch(() => undefined);
  263. await clearAppData();
  264. });
  265. it("插槽、问题行、崩溃恢复、卡死预算、重新加载、环境变量与退出收口", async function () {
  266. this.timeout(420000);
  267. requirePluginManualReview();
  268. await seedExtensionFixtures();
  269. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  270. afterElectronProcessExit: async () => {
  271. logCursor = (await readMainLog()).length;
  272. },
  273. });
  274. // 配好上游模型并进入真实草稿:草稿有预热会话,composer.status 的点击作用域是会话。
  275. await prepareV4ConversationE2E();
  276. await setCurrentElectronRendererContentSize(1400, 900);
  277. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  278. // (a) 激活后 composer.status 显示在用量圆环左边。
  279. await waitForSlotText(STATUS_ITEM, READY_TEXT, 60000);
  280. // 草稿没有用量数据时圆环不渲染;插槽紧挨模型控件组(圆环、模型选择器)之前。
  281. const layout = await browser.execute(
  282. (slotTestId, ringTestId, configTestId, modelTestId, id) => {
  283. const slot = document.querySelector<HTMLElement>(
  284. `[data-testid="${slotTestId}"][data-extension-item="${id}"]`,
  285. );
  286. const ring = document.querySelector<HTMLElement>(`[data-testid="${ringTestId}"]`);
  287. const model = document.querySelector<HTMLElement>(`[data-testid="${modelTestId}"]`);
  288. let next = slot?.nextElementSibling ?? null;
  289. while (next && next.getAttribute("data-testid") === slotTestId) {
  290. next = next.nextElementSibling;
  291. }
  292. return {
  293. beforeModelControls: next?.getAttribute("data-testid") === configTestId,
  294. ringPresent: Boolean(ring),
  295. slotRight: slot?.getBoundingClientRect().right ?? null,
  296. ringLeft: ring?.getBoundingClientRect().left ?? null,
  297. modelLeft: model?.getBoundingClientRect().left ?? null,
  298. ringFollowsSlot: ring
  299. ? Boolean(slot && slot.compareDocumentPosition(ring) & Node.DOCUMENT_POSITION_FOLLOWING)
  300. : null,
  301. };
  302. },
  303. TID_EXTENSION_COMPOSER_STATUS,
  304. TID_CHAT_CONTEXT_USAGE_TRIGGER,
  305. TID_V4_MODEL_CONFIG,
  306. TID_CHAT_MODEL_SELECT_TRIGGER,
  307. STATUS_ITEM,
  308. );
  309. evidence.layout = layout;
  310. expect(layout.beforeModelControls).toBe(true);
  311. if (layout.ringPresent) expect(layout.ringFollowsSlot).toBe(true);
  312. for (const right of [layout.ringLeft, layout.modelLeft]) {
  313. if (layout.slotRight !== null && right !== null) {
  314. expect(layout.slotRight).toBeLessThanOrEqual(right + 1);
  315. }
  316. }
  317. await waitForLog(
  318. (line) => line.includes("[e2e-ext-status@inline] activated in"),
  319. "activation log",
  320. );
  321. await waitForLog(
  322. (line) => /\[extension-host\] gen=1 contributions snapshot gen=1 rev=\d+/.test(line),
  323. "contributions snapshot log",
  324. );
  325. await waitForLog(
  326. (line) => line.includes("[extensions]") && line.includes("contributions snapshot gen=1"),
  327. "window host snapshot relay log",
  328. );
  329. // 静态声明归 Window Host(§16.1):它读清单生成静态表,只把合法、兼容的扩展声明交给扩展进程。
  330. // 静态表包含插件清单里的每个插件(隔离 HOME 里还有不带 extension 的内置插件),扩展只有 2 个合法兼容。
  331. const staticTableLine = await waitForLog(
  332. (line) =>
  333. line.includes("[extensions]") &&
  334. /static table rev=\d+ plugins=\d+ extensions=2 /.test(line),
  335. "the window host should build the static table from every inventory plugin",
  336. );
  337. evidence.staticTableLog = staticTableLine;
  338. expect(Number(/plugins=(\d+)/.exec(staticTableLine)?.[1])).toBeGreaterThanOrEqual(
  339. PLUGINS.length,
  340. );
  341. evidence.declarationsLog = await waitForLog(
  342. (line) =>
  343. line.includes("[extensions]") && line.includes("declarations pushed gen=1 extensions=2"),
  344. "the window host should push only valid, compatible extensions",
  345. );
  346. // 未知插槽 id 只记诊断;引用未声明视图的条目只让它自己不可用(不交给扩展进程)。
  347. evidence.ignoredSlotLog = await waitForLog(
  348. (line) =>
  349. line.includes("manifest ignored e2e-ext-status@inline") &&
  350. line.includes('slots["future.slot"]'),
  351. "an unknown slot id should be ignored with a diagnostic",
  352. );
  353. evidence.unusableItemLog = await waitForLog(
  354. (line) => line.includes("E2E_EXT_UNUSABLE_ITEM not-declared"),
  355. "the unusable item should not reach the extension host",
  356. );
  357. // 点击执行命令:作用域为当前会话(草稿为预热会话),扩展按该会话写入文字。
  358. await clickSlot(STATUS_ITEM);
  359. await waitForSlotText(STATUS_ITEM, "E2E #1");
  360. evidence.commandLog = await waitForLog(
  361. (line) => line.includes("E2E_EXT_COMMAND_RUN") && line.includes("clicks=1"),
  362. "command run log",
  363. );
  364. expect(evidence.commandLog).toContain("scope=session");
  365. // 运行时护栏:ctx 冻结、process.exit 被拦截、未声明 id 抛 not-declared、未捕获错误归因插件。
  366. const guardLines = (await readMainLog()).slice(logCursor);
  367. evidence.guards = guardLines.filter((line) =>
  368. /E2E_EXT_(CTX_FROZEN|EXIT_BLOCKED|NOT_DECLARED)|E2E_EXT_UNCAUGHT/.test(line),
  369. );
  370. expect(guardLines.some((line) => line.includes("E2E_EXT_CTX_FROZEN true"))).toBe(true);
  371. expect(guardLines.some((line) => line.includes("E2E_EXT_EXIT_BLOCKED internal"))).toBe(true);
  372. expect(guardLines.some((line) => line.includes("E2E_EXT_NOT_DECLARED not-declared"))).toBe(
  373. true,
  374. );
  375. await waitForLog(
  376. (line) =>
  377. line.includes("[e2e-ext-status@inline] uncaught exception") &&
  378. line.includes("E2E_EXT_UNCAUGHT"),
  379. "uncaught error should be logged with the plugin id",
  380. );
  381. // (e) 环境变量只有白名单里的键,外加设置页注入的网络变量。代理、No Proxy 与 CA 不在白名单里,只来自
  382. // 设置页(与 CLI 相同):capture 模式下 WDIO 把自己的代理与 CA 写进隔离 HOME 的 setting.json,所以这里
  383. // 可能出现。「设置页留空时一个都没有」由 PLM-EXT-H3(plugin-extension-network)断言。
  384. const envLine = await waitForLog((line) => line.includes("E2E_EXT_ENV_KEYS"), "env keys log");
  385. const envKeys = JSON.parse(
  386. envLine.slice(envLine.indexOf("[", envLine.indexOf("E2E_EXT_ENV_KEYS"))),
  387. ) as string[];
  388. evidence.envKeys = envKeys;
  389. const unexpected = envKeys.filter(
  390. (key) =>
  391. !ENV_ALLOWLIST.has(key) &&
  392. !PLATFORM_INJECTED_ENV.has(key) &&
  393. !SETTINGS_NETWORK_ENV.has(key),
  394. );
  395. evidence.envNotAllowlisted = envKeys.filter((key) => !ENV_ALLOWLIST.has(key));
  396. expect(unexpected).toEqual([]);
  397. expect(envKeys.some((key) => /OTEL|TELEMETRY|OAUTH|SECRET|TOKEN|BIGMODEL/i.test(key))).toBe(
  398. false,
  399. );
  400. expect(envKeys).toContain("ZCODE_PROCESS_LABEL");
  401. // (d) 启动页「扩展」分区:清单非法(悬停带字段路径)、版本不兼容、条目不可用。
  402. await openLauncher();
  403. await $(`[data-testid="${TID_SIDE_PANE_EXTENSIONS}"]`).waitForExist({ timeout: 15000 });
  404. const assertProblemRows = (problems: LauncherRow[]) => {
  405. const invalid = findRow(problems, "extension-problem:e2e-ext-invalid@inline");
  406. const incompatible = findRow(problems, "extension-problem:e2e-ext-incompatible@inline");
  407. const unusableItem = findRow(problems, "extension-problem:e2e-ext-status@inline");
  408. expect(invalid?.text).toContain("清单非法");
  409. expect(invalid?.title).toContain("extension.contributes.commands[0].titel");
  410. expect(incompatible?.text).toContain("版本不兼容");
  411. expect(incompatible?.title).toContain("^2.0.0");
  412. // 条目不可用只影响它自己:同一插件的 composer.status 与启动页条目照常。
  413. expect(unusableItem?.text).toContain("清单非法");
  414. expect(unusableItem?.title).toContain(BROKEN_ITEM_PATH);
  415. };
  416. const problems = await readLauncherRows(TID_SIDE_PANE_EXTENSION_PROBLEM);
  417. evidence.problems = problems;
  418. assertProblemRows(problems);
  419. // 静态条目:扩展进程运行时是普通的「打开」行。
  420. const panelRunning = findRow(
  421. await readLauncherRows(TID_SIDE_PANE_EXTENSION_VIEW_ITEM),
  422. `extension-view:${PANEL_ITEM}`,
  423. );
  424. evidence.panelRowRunning = panelRunning;
  425. expect(panelRunning?.text).toContain("E2E 状态面板");
  426. expect(panelRunning?.text).not.toContain("扩展已停止");
  427. // (g) 深浅主题、中英文截图:插槽与启动页分区(分区在启动页底部,先滚到可见)。
  428. await browser.execute((testId) => {
  429. document.querySelector(`[data-testid="${testId}"]`)?.scrollIntoView({ block: "center" });
  430. }, TID_SIDE_PANE_EXTENSIONS);
  431. const screenshots: string[] = [];
  432. for (const [locale, theme] of [
  433. ["zh-CN", "zai-light"],
  434. ["zh-CN", "zai-dark"],
  435. ["en-US", "zai-light"],
  436. ["en-US", "zai-dark"],
  437. ] as const) {
  438. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  439. screenshots.push(await capturePluginManualReview(CASE_ID, `slots-${locale}-${theme}`));
  440. }
  441. evidence.screenshots = screenshots;
  442. // 工具栏变窄时扩展条目最先收起(只留图标):任何其他档位收起时,扩展条目必须已收起。
  443. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 900, height: 900 });
  444. await browser.waitUntil(
  445. async () =>
  446. browser.execute(
  447. (testId) =>
  448. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid="${testId}"]`)).every(
  449. (element) => element.dataset.composerCompact === "true",
  450. ),
  451. TID_EXTENSION_COMPOSER_STATUS,
  452. ),
  453. { timeout: 10000, timeoutMsg: "extension items should collapse first in a narrow toolbar" },
  454. );
  455. const collapse = await browser.execute(() =>
  456. Array.from(document.querySelectorAll<HTMLElement>("[data-composer-collapse-priority]")).map(
  457. (element) => ({
  458. priority: element.dataset.composerCollapsePriority,
  459. compact: element.dataset.composerCompact ?? null,
  460. }),
  461. ),
  462. );
  463. evidence.narrowCollapse = collapse;
  464. screenshots.push(await capturePluginManualReview(CASE_ID, "composer-narrow-zh-CN-zai-light"));
  465. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  466. // (b) 杀掉扩展进程:gen + 1 重启,插槽文字由扩展重新设置(动态值随进程清空)。
  467. const first = await readStatusState();
  468. evidence.gen1Pid = first.pid;
  469. process.kill(first.pid, "SIGKILL");
  470. await waitForLog(
  471. (line) =>
  472. line.includes("[extension-host] gen=1 extension host exited") &&
  473. line.includes("intent=crash"),
  474. "gen=1 exit should be logged as a crash",
  475. );
  476. await waitForGenRunning(2);
  477. await browser.waitUntil(async () => (await readStatusState()).pid !== first.pid, {
  478. timeout: 30000,
  479. timeoutMsg: "extension should activate again in the new process",
  480. });
  481. await waitForSlotText(STATUS_ITEM, READY_TEXT);
  482. // (c) 卡死:死循环命令 15 秒左右被判卡死并重启(计入预算)。
  483. const hangStartedAt = Date.now();
  484. await waitForSlotText(HANG_ITEM, HANG_TEXT);
  485. await clickSlot(HANG_ITEM);
  486. await waitForLog(
  487. (line) => line.includes("[extension-host] gen=2 unresponsive"),
  488. "busy loop should be detected",
  489. 30000,
  490. );
  491. evidence.hangDetectedMs = Date.now() - hangStartedAt;
  492. expect(evidence.hangDetectedMs as number).toBeLessThan(25000);
  493. await waitForGenRunning(3);
  494. await waitForSlotText(HANG_ITEM, HANG_TEXT);
  495. // 第 3 次崩溃:最后一次自动重启,退避 4s。
  496. await clickSlot(HANG_ITEM);
  497. await waitForLog(
  498. (line) => line.includes("[extension-host] gen=3 restarting in 4000ms (restart 3/3)"),
  499. "the third crash should use the last backoff step",
  500. 30000,
  501. );
  502. await waitForGenRunning(4);
  503. await waitForSlotText(HANG_ITEM, HANG_TEXT);
  504. // 第 4 次崩溃:5 分钟内超过 3 次自动重启,预算耗尽,扩展进程停止。
  505. await clickSlot(HANG_ITEM);
  506. await waitForLog(
  507. (line) => line.includes("[extension-host] gen=4 status=stopped"),
  508. "crash budget should be exhausted",
  509. 30000,
  510. );
  511. await waitForSlotText(STATUS_ITEM, null);
  512. await openLauncher();
  513. await $(`[data-testid="${TID_SIDE_PANE_EXTENSIONS_STOPPED}"]`).waitForExist({ timeout: 15000 });
  514. evidence.stoppedRow = await browser.execute(
  515. (testId) => document.querySelector(`[data-testid="${testId}"]`)?.textContent ?? "",
  516. TID_SIDE_PANE_EXTENSIONS_STOPPED,
  517. );
  518. expect(evidence.stoppedRow).toContain("扩展已停止");
  519. expect(await $(`[data-testid="${TID_SIDE_PANE_EXTENSIONS_STOPPED}"]`).isDisplayed()).toBe(true);
  520. // 扩展进程停止后静态声明照常(§16.1):问题行都在;扩展目标的条目照常显示但不可用,
  521. // 标签为「扩展已停止」,操作改为「重新加载」。
  522. const stoppedProblems = await readLauncherRows(TID_SIDE_PANE_EXTENSION_PROBLEM);
  523. evidence.problemsWhileStopped = stoppedProblems;
  524. assertProblemRows(stoppedProblems);
  525. const panelStopped = findRow(
  526. await readLauncherRows(TID_SIDE_PANE_EXTENSION_VIEW_ITEM),
  527. `extension-view:${PANEL_ITEM}`,
  528. );
  529. evidence.panelRowStopped = panelStopped;
  530. expect(panelStopped?.text).toContain("E2E 状态面板");
  531. expect(panelStopped?.text).toContain("扩展已停止");
  532. expect(panelStopped?.text).toContain("重新加载");
  533. await browser.execute((testId) => {
  534. document.querySelector(`[data-testid="${testId}"]`)?.scrollIntoView({ block: "center" });
  535. }, TID_SIDE_PANE_EXTENSIONS_STOPPED);
  536. for (const [locale, theme] of [
  537. ["zh-CN", "zai-light"],
  538. ["en-US", "zai-dark"],
  539. ] as const) {
  540. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  541. screenshots.push(await capturePluginManualReview(CASE_ID, `stopped-${locale}-${theme}`));
  542. }
  543. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  544. // 命令中心「重新加载扩展」:清零预算并重启,已停止时也能用。
  545. await runReloadFromCommandCenter();
  546. await waitForLog(
  547. (line) => line.includes("reload requested; crash budget reset"),
  548. "reload should reach the supervisor",
  549. );
  550. await waitForGenRunning(5);
  551. await waitForSlotText(STATUS_ITEM, READY_TEXT);
  552. await $(`[data-testid="${TID_SIDE_PANE_EXTENSIONS_STOPPED}"]`).waitForExist({
  553. reverse: true,
  554. timeout: 15000,
  555. });
  556. // 重新加载会重读静态表;扩展进程恢复后条目回到「打开」。
  557. await waitForLog(
  558. (line) => line.includes("[extensions]") && /static table rev=\d+ .*\(reload\)/.test(line),
  559. "reload should re-read the static table",
  560. );
  561. const panelReloaded = findRow(
  562. await readLauncherRows(TID_SIDE_PANE_EXTENSION_VIEW_ITEM),
  563. `extension-view:${PANEL_ITEM}`,
  564. );
  565. evidence.panelRowReloaded = panelReloaded;
  566. expect(panelReloaded?.text).not.toContain("扩展已停止");
  567. // (f) 退出 App:扩展进程在退出收口内结束,没有残留进程。
  568. const last = await readStatusState();
  569. evidence.gen5Pid = last.pid;
  570. let aliveAfterQuit: boolean | null = null;
  571. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  572. afterElectronProcessExit: () => {
  573. aliveAfterQuit = isAlive(last.pid);
  574. },
  575. });
  576. evidence.aliveAfterQuit = aliveAfterQuit;
  577. expect(aliveAfterQuit).toBe(false);
  578. evidence.disposeLog = await waitForLog(
  579. (line) =>
  580. line.includes("[extension-host] gen=5 extension host exited") &&
  581. line.includes("intent=dispose"),
  582. "gen=5 should exit through the quit barrier",
  583. );
  584. evidence.lifecycle = (await readMainLog())
  585. .slice(logCursor)
  586. .filter((line) =>
  587. /status=|forked|paired|exited|unresponsive|budget|reload|activated|snapshot|static table|declarations|manifest/.test(
  588. line,
  589. ),
  590. );
  591. });
  592. });