plugin-extension-sessions.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. // PLM-EXT-P3A:扩展的会话读权限(docs/plugins/extension-host.md §17.2、§17.3、§17.7、§17.8、§17.10 第 1 步)。
  2. // 隔离 HOME:三个纯 JS fixture 扩展(test/e2e/fixtures/fs/plugins/plugin-extension-sessions/)经 plugins.dirs 加载:
  3. // - e2e-ext-sessions:清单声明 grants ["sessions.read"]。激活时与每次换语言时调 ctx.sessions.listSessions
  4. // 与 readSession(view: messages),日志只有数量、角色、id 与是否含测试标记。
  5. // - e2e-ext-sessions-nogrant:没有声明 grants,调用应报 not-declared。
  6. // - e2e-ext-sessions-late:带代码的扩展,初始禁用;已有扩展持有会话权限时,启用它要先确认。
  7. // 正式会话用 replay 创建:提示词带 upstream-e2e-ok,命中 provider-basic.json 的 upstream-provider-basic。
  8. // 运行时证据:Main 日志([extensions] / [extension-slots] / fixture 的 E2E_SESSIONS_*)、隔离 HOME 的
  9. // ~/.zcode/v2/extensions/grants.json 与 audit/*.jsonl、启动页与详情页 DOM。
  10. import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  11. import { join, resolve } from "node:path";
  12. import { EXTENSION_SESSION_CONSENT_REVISION } from "@zcode/shared/extension-host";
  13. import {
  14. TID_CONFIRM_DIALOG_CONFIRM,
  15. TID_EXTENSION_ENABLE_CONFIRM_DIALOG,
  16. TID_EXTENSION_GRANT_DIALOG,
  17. TID_EXTENSION_PERMISSIONS,
  18. TID_EXTENSION_PERMISSIONS_ACTION,
  19. TID_EXTENSION_PERMISSIONS_REVOKE,
  20. TID_SETTINGS_BACK_BUTTON,
  21. TID_SIDE_PANE_EXTENSION_GRANT,
  22. } from "@zcode/shared/test-ids";
  23. import {
  24. DEFAULT_WORKSPACE,
  25. clearAppData,
  26. clickTestIdByDom,
  27. getE2EAppDataPaths,
  28. } from "#e2e/helpers/desktop-app";
  29. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  30. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  31. import { createExtensionLog, openLauncher } from "#e2e/helpers/extension-host-views";
  32. import {
  33. prepareV4ConversationE2E,
  34. sendV4Prompt,
  35. waitForV4AssistantMessageContaining,
  36. waitForV4Pane,
  37. } from "#e2e/helpers/v4-conversation";
  38. import {
  39. capturePluginManualReview,
  40. clickPluginControl,
  41. openInstalledPluginSettingsDetail,
  42. openPluginManagementSettings,
  43. requirePluginManualReview,
  44. setPluginPresentation,
  45. waitForPluginControl,
  46. } from "#e2e/helpers/plugin-management-lifecycle";
  47. const CASE_ID = "PLM-EXT-P3A";
  48. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  49. const FIXTURE_ROOT = resolve(
  50. process.cwd(),
  51. "test/e2e/fixtures/fs/plugins/plugin-extension-sessions",
  52. );
  53. const PLUGIN = "e2e-ext-sessions";
  54. const PLUGIN_ID = `${PLUGIN}@inline`;
  55. const NOGRANT_ID = "e2e-ext-sessions-nogrant@inline";
  56. const LATE = "e2e-ext-sessions-late";
  57. const LATE_ID = `${LATE}@inline`;
  58. const PLUGINS = [PLUGIN, "e2e-ext-sessions-nogrant", LATE];
  59. // 标记让 fixture 判断 readSession 读到的是这条消息;审计文件里不能出现它。
  60. const MARKER = "E2E_EXT_SESSIONS";
  61. const PROMPT = `${MARKER}: Reply with exactly "upstream-e2e-ok" and no other text.`;
  62. const evidence: Record<string, unknown> = {};
  63. const screenshots: string[] = [];
  64. const log = createExtensionLog();
  65. function extensionsDataPath(...segments: string[]): string {
  66. return join(resolveE2EStorageRoot(), "v2", "extensions", ...segments);
  67. }
  68. /** 三个插件都进 plugins.dirs;e2e-ext-sessions-late 显式禁用,之后经设置页启用。 */
  69. async function seedFixtures(): Promise<void> {
  70. const target = join(getE2EAppDataPaths().homeDir, "fixtures", "extension-sessions");
  71. await mkdir(target, { recursive: true });
  72. for (const name of PLUGINS) {
  73. await cp(join(FIXTURE_ROOT, name), join(target, name), { recursive: true, force: true });
  74. }
  75. const configPath = join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "config.json");
  76. const config = JSON.parse(await readFile(configPath, "utf8").catch(() => "{}")) as Record<
  77. string,
  78. unknown
  79. >;
  80. const plugins = (config.plugins ?? {}) as Record<string, unknown>;
  81. await mkdir(join(getE2EAppDataPaths().homeDir, ".zcode", "cli"), { recursive: true });
  82. await writeFile(
  83. configPath,
  84. JSON.stringify(
  85. {
  86. ...config,
  87. plugins: {
  88. ...plugins,
  89. enabled: true,
  90. dirs: PLUGINS.map((name) => join(target, name)),
  91. enabledPlugins: {
  92. ...((plugins.enabledPlugins ?? {}) as Record<string, boolean>),
  93. [PLUGIN_ID]: true,
  94. [NOGRANT_ID]: true,
  95. [LATE_ID]: false,
  96. },
  97. },
  98. },
  99. null,
  100. 2,
  101. ),
  102. );
  103. }
  104. async function readGrantsFile(): Promise<Record<string, unknown> | null> {
  105. const text = await readFile(extensionsDataPath("grants.json"), "utf8").catch(() => null);
  106. return text ? (JSON.parse(text) as Record<string, unknown>) : null;
  107. }
  108. /** 隔离 HOME 里全部审计文件的原文与解析后的行。 */
  109. async function readAudit(): Promise<{ text: string; lines: Array<Record<string, unknown>> }> {
  110. const dir = extensionsDataPath("audit");
  111. const names = (await readdir(dir).catch(() => [] as string[])).filter((name) =>
  112. name.endsWith(".jsonl"),
  113. );
  114. let text = "";
  115. for (const name of names.sort()) text += await readFile(join(dir, name), "utf8");
  116. return {
  117. text,
  118. lines: text
  119. .split("\n")
  120. .filter(Boolean)
  121. .map((line) => JSON.parse(line) as Record<string, unknown>),
  122. };
  123. }
  124. /** 等 from 行之后出现满足条件的日志行(换语言会触发探测;旧的探测行不能算)。 */
  125. async function waitForLogAfter(
  126. from: number,
  127. predicate: (line: string) => boolean,
  128. message: string,
  129. timeout = 30000,
  130. ): Promise<string> {
  131. let found = "";
  132. await browser.waitUntil(
  133. async () => {
  134. found = (await log.lines()).slice(from).find(predicate) ?? "";
  135. return Boolean(found);
  136. },
  137. { timeout, interval: 500, timeoutMsg: message },
  138. );
  139. return found;
  140. }
  141. async function capture(label: string): Promise<void> {
  142. screenshots.push(await capturePluginManualReview(CASE_ID, label));
  143. }
  144. /**
  145. * 打开右侧面板的启动页并确认它真的可见:窄窗口或换主题后面板可能收起但保留 DOM,
  146. * 按「可见」判断,不按「存在」(与 PLM-EXT-2A 相同)。
  147. */
  148. async function openVisibleLauncher(): Promise<void> {
  149. await openLauncher();
  150. await browser.waitUntil(
  151. async () => {
  152. if (await $('[data-side-pane-open-tab-item="browser"]').isDisplayed()) return true;
  153. // 与产品 ⌥⌘B 共用真实 workspace shortcut。
  154. await browser.execute(() => {
  155. window.dispatchEvent(
  156. new KeyboardEvent("keydown", {
  157. key: "b",
  158. code: "KeyB",
  159. altKey: true,
  160. metaKey: true,
  161. bubbles: true,
  162. cancelable: true,
  163. }),
  164. );
  165. });
  166. return false;
  167. },
  168. { timeout: 15000, interval: 1000, timeoutMsg: "side pane launcher should be visible" },
  169. );
  170. }
  171. function grantRowSelector(pluginId: string): string {
  172. return `[data-testid="${TID_SIDE_PANE_EXTENSION_GRANT}"][data-side-pane-open-tab-item="extension-grant:${pluginId}"]`;
  173. }
  174. /** 启动页「需要授权」行(`extension-grant:<pluginId>`)的文本;没有这一行时为 null。 */
  175. async function readGrantRow(pluginId: string): Promise<string | null> {
  176. return browser.execute((selector) => {
  177. const row = document.querySelector<HTMLElement>(selector);
  178. return row ? (row.textContent ?? "") : null;
  179. }, grantRowSelector(pluginId));
  180. }
  181. /** 这一行可见(面板展开)后滚到中间,供截图与点击。 */
  182. async function waitForVisibleGrantRow(pluginId: string, message: string): Promise<void> {
  183. await openVisibleLauncher();
  184. await browser.waitUntil(async () => $(grantRowSelector(pluginId)).isDisplayed(), {
  185. timeout: 30000,
  186. interval: 300,
  187. timeoutMsg: message,
  188. });
  189. await browser.execute((selector) => {
  190. document.querySelector(selector)?.scrollIntoView({ block: "center" });
  191. }, grantRowSelector(pluginId));
  192. }
  193. async function clickGrantRow(pluginId: string): Promise<void> {
  194. const clicked = await browser.execute(
  195. (rowTestId, id) => {
  196. const row = document.querySelector<HTMLElement>(
  197. `[data-testid="${rowTestId}"][data-side-pane-open-tab-item="extension-grant:${id}"]`,
  198. );
  199. row?.scrollIntoView({ block: "center" });
  200. row?.click();
  201. return Boolean(row);
  202. },
  203. TID_SIDE_PANE_EXTENSION_GRANT,
  204. pluginId,
  205. );
  206. if (!clicked) throw new Error(`the launcher has no grant row for ${pluginId}`);
  207. }
  208. /** ConfirmDialog 的内容层(按 testId):标题与正文。 */
  209. async function readDialog(dialogTestId: string): Promise<string | null> {
  210. return browser.execute((id) => {
  211. const dialog = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  212. return dialog ? (dialog.innerText ?? "") : null;
  213. }, dialogTestId);
  214. }
  215. async function waitForDialog(dialogTestId: string, message: string): Promise<string> {
  216. let text: string | null = null;
  217. await browser.waitUntil(
  218. async () => {
  219. text = await readDialog(dialogTestId);
  220. return Boolean(text);
  221. },
  222. { timeout: 15000, interval: 200, timeoutMsg: message },
  223. );
  224. return text!;
  225. }
  226. async function confirmDialog(dialogTestId: string): Promise<void> {
  227. await browser.execute(
  228. (id, confirmTestId) => {
  229. document
  230. .querySelector<HTMLElement>(`[data-testid="${id}"] [data-testid="${confirmTestId}"]`)
  231. ?.click();
  232. },
  233. dialogTestId,
  234. TID_CONFIRM_DIALOG_CONFIRM,
  235. );
  236. await browser.waitUntil(async () => (await readDialog(dialogTestId)) === null, {
  237. timeout: 15000,
  238. timeoutMsg: `${dialogTestId} should close after confirming`,
  239. });
  240. }
  241. /** 按 Esc 关闭 ConfirmDialog(等同取消)。 */
  242. async function dismissDialog(dialogTestId: string): Promise<void> {
  243. await browser.keys("Escape");
  244. await browser.waitUntil(async () => (await readDialog(dialogTestId)) === null, {
  245. timeout: 15000,
  246. timeoutMsg: `${dialogTestId} should close on Escape`,
  247. });
  248. }
  249. /** 设置页插件列表里该插件启用开关的状态(Radix Switch 的 aria-checked)。 */
  250. async function readSwitchChecked(pluginId: string): Promise<boolean | null> {
  251. return browser.execute((id) => {
  252. const element = document.querySelector<HTMLElement>(
  253. `[data-testid="plugin-settings-enabled-switch"][data-plugin-id="${id}"]`,
  254. );
  255. return element ? element.getAttribute("aria-checked") === "true" : null;
  256. }, pluginId);
  257. }
  258. interface PermissionsUi {
  259. status: string | null;
  260. text: string;
  261. actions: Array<{ capability: string; grant: string }>;
  262. }
  263. async function readPermissions(pluginId: string): Promise<PermissionsUi | null> {
  264. return browser.execute(
  265. (sectionTestId, actionTestId, id) => {
  266. const section = document.querySelector<HTMLElement>(
  267. `[data-testid="${sectionTestId}"][data-plugin-id="${id}"]`,
  268. );
  269. if (!section) return null;
  270. return {
  271. status: section.dataset.grantStatus ?? null,
  272. text: section.innerText ?? "",
  273. actions: Array.from(
  274. section.querySelectorAll<HTMLElement>(`[data-testid="${actionTestId}"]`),
  275. ).map((row) => ({
  276. capability: row.dataset.capability ?? "",
  277. grant: row.dataset.grant ?? "",
  278. })),
  279. };
  280. },
  281. TID_EXTENSION_PERMISSIONS,
  282. TID_EXTENSION_PERMISSIONS_ACTION,
  283. pluginId,
  284. );
  285. }
  286. async function waitForPermissions(
  287. pluginId: string,
  288. predicate: (ui: PermissionsUi) => boolean,
  289. message: string,
  290. ): Promise<PermissionsUi> {
  291. let latest: PermissionsUi | null = null;
  292. try {
  293. await browser.waitUntil(
  294. async () => {
  295. latest = await readPermissions(pluginId);
  296. return Boolean(latest && predicate(latest));
  297. },
  298. { timeout: 30000, interval: 300 },
  299. );
  300. } catch {
  301. // 失败时带上最后一次读数(timeoutMsg 在等待开始前就求值了,拿不到最后的读数)。
  302. throw new Error(`${message}: ${JSON.stringify(latest)}`);
  303. }
  304. return latest!;
  305. }
  306. describe("PLM-EXT-P3A 扩展的会话读权限、授权与审计", () => {
  307. after(async () => {
  308. evidence.screenshots = screenshots;
  309. await writeFile(
  310. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-p3a-evidence.json"),
  311. JSON.stringify(evidence, null, 2),
  312. ).catch(() => undefined);
  313. await clearAppData();
  314. });
  315. it("未授权报 not-granted,授权后能读会话,撤销后又报 not-granted;审计不含内容;启用确认", async function () {
  316. this.timeout(600000);
  317. requirePluginManualReview();
  318. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  319. await seedFixtures();
  320. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  321. afterElectronProcessExit: () => log.mark(),
  322. });
  323. await prepareV4ConversationE2E();
  324. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  325. // (a) 未授权:扩展照常激活,会话能力报 not-granted;清单没有声明档位的扩展报 not-declared。
  326. evidence.notGranted = await log.waitFor(
  327. (line) =>
  328. line.includes(`E2E_SESSIONS_LIST plugin=${PLUGIN_ID} reason=activate`) &&
  329. line.includes("error="),
  330. "the sessions extension should probe on activation",
  331. 60000,
  332. );
  333. expect(String(evidence.notGranted)).toContain("error=not-granted");
  334. evidence.notDeclared = await log.waitFor(
  335. (line) => line.includes(`E2E_SESSIONS_NOGRANT plugin=${NOGRANT_ID}`),
  336. "the extension without grants should probe on activation",
  337. 60000,
  338. );
  339. expect(String(evidence.notDeclared)).toContain("error=not-declared");
  340. expect(await readGrantsFile()).toBeNull();
  341. // (b) 启动页「扩展」分区显示「需要授权」;没有声明档位的插件不显示。
  342. await waitForVisibleGrantRow(PLUGIN_ID, "the launcher should show the needs-consent row");
  343. evidence.grantRow = await readGrantRow(PLUGIN_ID);
  344. expect(String(evidence.grantRow)).toContain("需要授权");
  345. expect(String(evidence.grantRow)).toContain("读取会话");
  346. expect(await readGrantRow(NOGRANT_ID)).toBeNull();
  347. for (const [locale, theme] of [
  348. ["zh-CN", "zai-light"],
  349. ["zh-CN", "zai-dark"],
  350. ["en-US", "zai-light"],
  351. ["en-US", "zai-dark"],
  352. ] as const) {
  353. await setPluginPresentation({ locale, theme, width: 1400, height: 900 });
  354. await waitForVisibleGrantRow(
  355. PLUGIN_ID,
  356. "the needs-consent row should stay after switching presentation",
  357. );
  358. await capture(`launcher-needs-consent-${locale}-${theme}`);
  359. }
  360. evidence.grantRowEnglish = await readGrantRow(PLUGIN_ID);
  361. expect(String(evidence.grantRowEnglish)).toContain("Needs permission");
  362. // (c) 授权对话框(spec 原文)→ 授权:grants.json 有记录,启动页的行消失。
  363. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  364. await waitForVisibleGrantRow(
  365. PLUGIN_ID,
  366. "the needs-consent row should be visible before granting",
  367. );
  368. await clickGrantRow(PLUGIN_ID);
  369. evidence.grantDialog = await waitForDialog(
  370. TID_EXTENSION_GRANT_DIALOG,
  371. "the grant row should open the consent dialog",
  372. );
  373. expect(String(evidence.grantDialog)).toContain(`允许「${PLUGIN}」读取会话?`);
  374. expect(String(evidence.grantDialog)).toContain(
  375. "扩展代码与其他扩展在同一个进程运行,彼此没有隔离。",
  376. );
  377. expect(String(evidence.grantDialog)).toContain("插件发起的操作会标出来源,并写入审计日志。");
  378. await capture("grant-dialog-zh-CN-zai-light");
  379. // 取消(Esc)不授权:没有记录,这一行还在。对话框文案在打开时按当时的语言生成,所以换语言后重新打开截图。
  380. await dismissDialog(TID_EXTENSION_GRANT_DIALOG);
  381. expect(await readGrantsFile()).toBeNull();
  382. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  383. await waitForVisibleGrantRow(PLUGIN_ID, "the needs-consent row should stay after cancelling");
  384. await clickGrantRow(PLUGIN_ID);
  385. evidence.grantDialogEnglish = await waitForDialog(
  386. TID_EXTENSION_GRANT_DIALOG,
  387. "the grant row should open the consent dialog again",
  388. );
  389. expect(String(evidence.grantDialogEnglish)).toContain(`Allow “${PLUGIN}” to read sessions?`);
  390. await capture("grant-dialog-en-US-zai-dark");
  391. await confirmDialog(TID_EXTENSION_GRANT_DIALOG);
  392. await browser.waitUntil(
  393. async () => {
  394. const plugins = ((await readGrantsFile())?.plugins ?? {}) as Record<string, unknown>;
  395. return Boolean(plugins[PLUGIN_ID]);
  396. },
  397. { timeout: 15000, timeoutMsg: "grants.json should record the grant" },
  398. );
  399. const grantsFile = await readGrantsFile();
  400. evidence.grantsFile = grantsFile;
  401. expect(grantsFile).toMatchObject({
  402. version: 1,
  403. plugins: {
  404. [PLUGIN_ID]: {
  405. grants: ["sessions.read"],
  406. consentedVersion: "1.0.0",
  407. consentRevision: EXTENSION_SESSION_CONSENT_REVISION,
  408. },
  409. },
  410. });
  411. await browser.waitUntil(async () => (await readGrantRow(PLUGIN_ID)) === null, {
  412. timeout: 15000,
  413. timeoutMsg: "the needs-consent row should disappear after granting",
  414. });
  415. evidence.grantLog = await log.waitFor(
  416. (line) => line.includes(`extension grants granted plugin=${PLUGIN_ID} tiers=sessions.read`),
  417. "the Window Host should log the grant",
  418. );
  419. // (d) 发一条 replay 消息建正式会话;换语言触发探测:listSessions 有这个会话,readSession 读到它的消息。
  420. // 先回到中文,后面换成英文时 env.onDidChange 才会触发。
  421. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  422. await sendV4Prompt(PROMPT);
  423. const session = await waitForV4Pane(
  424. (snapshot) => Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  425. "the draft should become a session after the first send",
  426. 60000,
  427. );
  428. const sessionId = session.sessionId ?? "";
  429. evidence.sessionId = sessionId;
  430. // 录制的回复是 deepseek-e2e-ok(provider-basic.json 的 upstream-provider-basic)。
  431. await waitForV4AssistantMessageContaining("deepseek-e2e-ok");
  432. const beforeEnglish = (await log.lines()).length;
  433. await setPluginPresentation({ locale: "en-US", theme: "zai-light", width: 1400, height: 900 });
  434. evidence.grantedList = await waitForLogAfter(
  435. beforeEnglish,
  436. (line) =>
  437. line.includes(`E2E_SESSIONS_LIST plugin=${PLUGIN_ID} reason=locale-en-US`) &&
  438. line.includes(" ok "),
  439. "listSessions should succeed after granting",
  440. );
  441. expect(String(evidence.grantedList)).toContain(sessionId);
  442. evidence.grantedRead = await waitForLogAfter(
  443. beforeEnglish,
  444. (line) =>
  445. line.includes(`E2E_SESSIONS_READ plugin=${PLUGIN_ID} reason=locale-en-US id=${sessionId}`),
  446. "readSession should return the session messages",
  447. );
  448. expect(String(evidence.grantedRead)).toContain("view=messages");
  449. expect(String(evidence.grantedRead)).toContain("roles=assistant,user");
  450. expect(String(evidence.grantedRead)).toContain("marker=true");
  451. // (e) 已有扩展持有会话权限:在设置页启用另一个带代码的扩展,要先确认;确认后它激活。
  452. await openPluginManagementSettings();
  453. await waitForPluginControl("plugin-settings-enabled-switch", { pluginId: LATE_ID }, 30000);
  454. await clickPluginControl("plugin-settings-enabled-switch", { pluginId: LATE_ID });
  455. evidence.enableDialog = await waitForDialog(
  456. TID_EXTENSION_ENABLE_CONFIRM_DIALOG,
  457. "enabling a code extension while grants are held should ask for confirmation",
  458. );
  459. // 标题用设置页的插件显示名(E2e Ext Sessions Late),持有者用静态表里的插件名。
  460. expect(String(evidence.enableDialog)).toMatch(/^Enable “.+”\?/u);
  461. expect(String(evidence.enableDialog)).toContain("its code can use these permissions too");
  462. expect(String(evidence.enableDialog)).toContain(`“${PLUGIN}” (Read sessions)`);
  463. await capture("enable-confirm-en-US-zai-light");
  464. // 取消(Esc)不启用:开关仍是关,扩展没有激活。再换语言重新打开确认。
  465. await dismissDialog(TID_EXTENSION_ENABLE_CONFIRM_DIALOG);
  466. expect(await readSwitchChecked(LATE_ID)).toBe(false);
  467. expect((await log.lines()).some((line) => line.includes("E2E_SESSIONS_LATE_ACTIVATED"))).toBe(
  468. false,
  469. );
  470. await setPluginPresentation({ locale: "zh-CN", theme: "zai-dark", width: 1400, height: 900 });
  471. await clickPluginControl("plugin-settings-enabled-switch", { pluginId: LATE_ID });
  472. evidence.enableDialogChinese = await waitForDialog(
  473. TID_EXTENSION_ENABLE_CONFIRM_DIALOG,
  474. "enabling again should ask for confirmation again",
  475. );
  476. expect(String(evidence.enableDialogChinese)).toContain(`「${PLUGIN}」(读取会话)`);
  477. await capture("enable-confirm-zh-CN-zai-dark");
  478. await confirmDialog(TID_EXTENSION_ENABLE_CONFIRM_DIALOG);
  479. evidence.lateActivated = await log.waitFor(
  480. (line) => line.includes(`E2E_SESSIONS_LATE_ACTIVATED plugin=${LATE_ID}`),
  481. "the late extension should activate after confirming",
  482. 60000,
  483. );
  484. // (f) 插件详情页「权限」区块:已授予、最近操作有授权一行;撤销后回到需要授权。
  485. await openInstalledPluginSettingsDetail(PLUGIN_ID);
  486. const granted = await waitForPermissions(
  487. PLUGIN_ID,
  488. (ui) => ui.status === "granted" && ui.actions.some((a) => a.capability === "grants.grant"),
  489. "the permissions section should show the grant",
  490. );
  491. evidence.permissionsGranted = granted;
  492. await capture("permissions-granted-zh-CN-zai-dark");
  493. await setPluginPresentation({ locale: "en-US", theme: "zai-light", width: 1400, height: 900 });
  494. await capture("permissions-granted-en-US-zai-light");
  495. await clickPluginControl(TID_EXTENSION_PERMISSIONS_REVOKE, { pluginId: PLUGIN_ID });
  496. const revoked = await waitForPermissions(
  497. PLUGIN_ID,
  498. (ui) =>
  499. ui.status === "needs-consent" && ui.actions.some((a) => a.capability === "grants.revoke"),
  500. "the permissions section should show the revoke",
  501. );
  502. evidence.permissionsRevoked = revoked;
  503. expect(revoked.actions.slice(0, 2)).toEqual([
  504. { capability: "grants.revoke", grant: "sessions.read" },
  505. { capability: "grants.grant", grant: "sessions.read" },
  506. ]);
  507. await capture("permissions-revoked-en-US-zai-light");
  508. const grantsAfterRevoke = await readGrantsFile();
  509. evidence.grantsAfterRevoke = grantsAfterRevoke;
  510. expect(
  511. Object.keys((grantsAfterRevoke?.plugins ?? {}) as Record<string, unknown>),
  512. ).not.toContain(PLUGIN_ID);
  513. // (g) 撤销后:换语言再探测,又报 not-granted。
  514. const beforeChinese = (await log.lines()).length;
  515. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  516. evidence.revokedList = await waitForLogAfter(
  517. beforeChinese,
  518. (line) => line.includes(`E2E_SESSIONS_LIST plugin=${PLUGIN_ID} reason=locale-zh-CN`),
  519. "the probe should run after revoking",
  520. );
  521. expect(String(evidence.revokedList)).toContain("error=not-granted");
  522. // (h) 启动页又显示「需要授权」。
  523. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  524. timeout: 15000,
  525. timeoutMsg: "settings back button should be visible",
  526. });
  527. await waitForVisibleGrantRow(
  528. PLUGIN_ID,
  529. "the launcher should show the needs-consent row again after revoking",
  530. );
  531. await capture("launcher-needs-consent-again-zh-CN-zai-light");
  532. // (i) 审计文件:授权与撤销各一行,字段只有标识与结果,不含提示词、标记与正文。
  533. const audit = await readAudit();
  534. evidence.auditLines = audit.lines;
  535. const own = audit.lines.filter((line) => line.pluginId === PLUGIN_ID);
  536. expect(own.map((line) => line.capability)).toEqual(["grants.grant", "grants.revoke"]);
  537. for (const line of own) {
  538. expect(line).toMatchObject({ v: 1, grant: "sessions.read", outcome: "ok" });
  539. expect(typeof line.ts).toBe("number");
  540. }
  541. expect(audit.text).not.toContain(MARKER);
  542. expect(audit.text).not.toContain("upstream-e2e-ok");
  543. expect(audit.text).not.toContain("deepseek-e2e-ok");
  544. expect(audit.text).not.toContain(getE2EAppDataPaths().homeDir);
  545. });
  546. });