plugin-extension-sessions-read.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. // PLM-EXT-P3B:扩展的会话读连接与商店安装后的激活确认(docs/plugins/extension-host.md §17.3、§17.5、§17.7、
  2. // §17.10 第 2 步)。
  3. // 隔离 HOME:
  4. // - 纯 JS fixture 扩展 e2e-ext-reads(test/e2e/fixtures/fs/plugins/plugin-extension-reads/)经 plugins.dirs
  5. // 加载,清单声明 sessions.read;授权记录预先写进隔离 HOME 的 grants.json(授权流程由 PLM-EXT-P3A 覆盖)。
  6. // 它订阅会话列表;有 9 个种子会话时做一次上限探测;观察最近的非种子会话的行与会话状态,视图显示镜像的行。
  7. // - 9 个种子会话用 seedProviderReadinessHistoryFixture 写进 CLI DB 与 tasks-index(只在 App 退出后写)。
  8. // - 本地插件市场 store-market(两个带扩展代码与技能的插件),经设置页的插件商店安装。
  9. // 模型用 replay:提示词带 upstream-e2e-ok,命中 plugin-extension-sessions-read.json(回复 deepseek-e2e-ok)。
  10. // 运行时证据:Main 日志([extensions] 的 session read connection / session mirror / activation 行与 fixture 的
  11. // E2E_READS_* / E2E_STORE_*)、隔离 HOME 的 grants.json、视图页面 DOM、截图。
  12. import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
  13. import { join, resolve } from "node:path";
  14. import {
  15. TID_CONFIRM_DIALOG_CONFIRM,
  16. TID_EXTENSION_ACTIVATION_DIALOG,
  17. TID_SIDE_PANE_EXTENSION_ACTIVATION,
  18. } from "@zcode/shared/test-ids";
  19. import {
  20. DEFAULT_WORKSPACE,
  21. clearAppData,
  22. clickTestIdByDom,
  23. getE2EAppDataPaths,
  24. } from "#e2e/helpers/desktop-app";
  25. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  26. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  27. import { seedProviderReadinessHistoryFixture } from "#e2e/helpers/provider-readiness-history-fixture";
  28. import { ServiceChannels } from "@zcode/shared";
  29. import {
  30. callHandoffHost,
  31. installHandoffRpcProbe,
  32. restoreHandoffProbes,
  33. } from "#e2e/helpers/remote-project-handoff-probe";
  34. import {
  35. createExtensionLog,
  36. openLauncher,
  37. openLauncherView,
  38. reloadExtensionsFromCommandCenter,
  39. waitForViewPage,
  40. waitForViewPane,
  41. } from "#e2e/helpers/extension-host-views";
  42. import {
  43. prepareV4ConversationE2E,
  44. sendV4Prompt,
  45. waitForV4AssistantMessageContaining,
  46. waitForV4Pane,
  47. } from "#e2e/helpers/v4-conversation";
  48. import {
  49. addMarketplaceSourceThroughAgent,
  50. capturePluginManualReview,
  51. clickPluginControl,
  52. getPluginList,
  53. getPluginReferenceCatalog,
  54. installPluginThroughUi,
  55. openPluginCard,
  56. openPluginSettings,
  57. requirePluginManualReview,
  58. setPluginPresentation,
  59. waitUntilPluginOverview,
  60. } from "#e2e/helpers/plugin-management-lifecycle";
  61. const CASE_ID = "PLM-EXT-P3B";
  62. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  63. const FIXTURE_ROOT = resolve(process.cwd(), "test/e2e/fixtures/fs/plugins/plugin-extension-reads");
  64. const CLI_ENTRY = resolve(process.cwd(), "../../apps/zcode-cli/packages/cli/dist/zcode.cjs");
  65. const PLUGIN = "e2e-ext-reads";
  66. const PLUGIN_ID = `${PLUGIN}@inline`;
  67. /** 长历史的轮数:行镜像的窗口装不下,要往前翻页(与原 PLM-JARVIS-1 相同)。 */
  68. const HISTORY_ROUNDS = 40;
  69. const VIEW_ID = `${PLUGIN_ID}/rows`;
  70. const LAUNCHER_ITEM = `${PLUGIN_ID}/open-rows`;
  71. const MARKET = "e2e-ext-store-market";
  72. const STORE_A = `e2e-ext-store-a@${MARKET}`;
  73. const STORE_B = `e2e-ext-store-b@${MARKET}`;
  74. const SEED_COUNT = 9;
  75. const MARKER = "E2E_EXT_READS";
  76. const PROMPT = `${MARKER}: Reply with exactly "upstream-e2e-ok" and no other text.`;
  77. // 录制的回复(plugin-extension-sessions-read.json 的 plugin-extension-sessions-read-1)。
  78. const REPLY = "deepseek-e2e-ok";
  79. const evidence: Record<string, unknown> = {};
  80. const screenshots: string[] = [];
  81. const log = createExtensionLog();
  82. function fixturesDir(): string {
  83. return join(getE2EAppDataPaths().homeDir, "fixtures", "extension-reads");
  84. }
  85. function grantsPath(): string {
  86. return join(resolveE2EStorageRoot(), "v2", "extensions", "grants.json");
  87. }
  88. async function readGrantsFile(): Promise<Record<string, unknown> | null> {
  89. const text = await readFile(grantsPath(), "utf8").catch(() => null);
  90. return text ? (JSON.parse(text) as Record<string, unknown>) : null;
  91. }
  92. async function activationOf(pluginId: string): Promise<string | null> {
  93. const activations = ((await readGrantsFile())?.activations ?? {}) as Record<
  94. string,
  95. { state?: string }
  96. >;
  97. return activations[pluginId]?.state ?? null;
  98. }
  99. /** fixture 插件进 plugins.dirs 并启用;授权记录预先写好(授权流程由 PLM-EXT-P3A 覆盖)。 */
  100. async function seedPlugin(): Promise<void> {
  101. const target = fixturesDir();
  102. await mkdir(target, { recursive: true });
  103. await cp(join(FIXTURE_ROOT, PLUGIN), join(target, PLUGIN), { recursive: true, force: true });
  104. const configPath = join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "config.json");
  105. const config = JSON.parse(await readFile(configPath, "utf8").catch(() => "{}")) as Record<
  106. string,
  107. unknown
  108. >;
  109. const plugins = (config.plugins ?? {}) as Record<string, unknown>;
  110. await mkdir(join(getE2EAppDataPaths().homeDir, ".zcode", "cli"), { recursive: true });
  111. await writeFile(
  112. configPath,
  113. JSON.stringify(
  114. {
  115. ...config,
  116. plugins: {
  117. ...plugins,
  118. enabled: true,
  119. dirs: [join(target, PLUGIN)],
  120. enabledPlugins: {
  121. ...((plugins.enabledPlugins ?? {}) as Record<string, boolean>),
  122. [PLUGIN_ID]: true,
  123. },
  124. },
  125. },
  126. null,
  127. 2,
  128. ),
  129. );
  130. await mkdir(join(resolveE2EStorageRoot(), "v2", "extensions"), { recursive: true });
  131. await writeFile(
  132. grantsPath(),
  133. JSON.stringify({
  134. version: 1,
  135. plugins: {
  136. // 故意不写 consentRevision(旧格式):只读档位的含义没变,旧记录照常生效(§17.12)。
  137. [PLUGIN_ID]: {
  138. grants: ["sessions.read"],
  139. consentedVersion: "1.0.0",
  140. consentedAt: Date.now(),
  141. },
  142. },
  143. }),
  144. );
  145. }
  146. /** 9 个种子会话(标题以 E2E_READS_SEED_ 开头),只在 App 退出后写。 */
  147. async function seedSessions(): Promise<void> {
  148. const home = getE2EAppDataPaths().homeDir;
  149. for (let index = 0; index < SEED_COUNT; index += 1) {
  150. await seedProviderReadinessHistoryFixture({
  151. cliEntryPoint: CLI_ENTRY,
  152. e2eHomeDir: home,
  153. workspacePath: DEFAULT_WORKSPACE,
  154. history: {
  155. sessionId: `sess_e2e_reads_seed_${index}`,
  156. title: `E2E_READS_SEED_${index}`,
  157. userText: `E2E_READS_SEED_USER_${index}`,
  158. assistantText: `E2E_READS_SEED_REPLY_${index}`,
  159. modelId: "missing-model",
  160. runtimeProviderId: "missing-provider",
  161. taskProviderId: "glm",
  162. assistantInputTokens: 0,
  163. assistantOutputTokens: 0,
  164. },
  165. });
  166. }
  167. }
  168. async function readFixtureState(): Promise<{ pid: number; activatedAt: number } | null> {
  169. const text = await readFile(join(fixturesDir(), "e2e-ext-reads-state.json"), "utf8").catch(
  170. () => null,
  171. );
  172. return text ? (JSON.parse(text) as { pid: number; activatedAt: number }) : null;
  173. }
  174. async function waitForLogAfter(
  175. from: number,
  176. predicate: (line: string) => boolean,
  177. message: string,
  178. timeout = 60000,
  179. ): Promise<string> {
  180. let found = "";
  181. await browser.waitUntil(
  182. async () => {
  183. found = (await log.lines()).slice(from).find(predicate) ?? "";
  184. return Boolean(found);
  185. },
  186. { timeout, interval: 500, timeoutMsg: message },
  187. );
  188. return found;
  189. }
  190. async function capture(label: string): Promise<void> {
  191. screenshots.push(await capturePluginManualReview(CASE_ID, label));
  192. }
  193. /** 打开右侧面板的启动页并确认它真的可见(与 PLM-EXT-P3A 相同)。 */
  194. async function openVisibleLauncher(): Promise<void> {
  195. await openLauncher();
  196. await browser.waitUntil(
  197. async () => {
  198. if (await $('[data-side-pane-open-tab-item="browser"]').isDisplayed()) return true;
  199. await browser.execute(() => {
  200. window.dispatchEvent(
  201. new KeyboardEvent("keydown", {
  202. key: "b",
  203. code: "KeyB",
  204. altKey: true,
  205. metaKey: true,
  206. bubbles: true,
  207. cancelable: true,
  208. }),
  209. );
  210. });
  211. return false;
  212. },
  213. { timeout: 15000, interval: 1000, timeoutMsg: "side pane launcher should be visible" },
  214. );
  215. }
  216. function activationRowSelector(pluginId: string): string {
  217. return `[data-testid="${TID_SIDE_PANE_EXTENSION_ACTIVATION}"][data-side-pane-open-tab-item="extension-activation:${pluginId}"]`;
  218. }
  219. async function readActivationRow(pluginId: string): Promise<string | null> {
  220. return browser.execute((selector) => {
  221. const row = document.querySelector<HTMLElement>(selector);
  222. return row ? (row.textContent ?? "") : null;
  223. }, activationRowSelector(pluginId));
  224. }
  225. async function waitForVisibleActivationRow(pluginId: string, message: string): Promise<void> {
  226. await openVisibleLauncher();
  227. await browser.waitUntil(async () => $(activationRowSelector(pluginId)).isDisplayed(), {
  228. timeout: 30000,
  229. interval: 300,
  230. timeoutMsg: message,
  231. });
  232. await browser.execute((selector) => {
  233. document.querySelector(selector)?.scrollIntoView({ block: "center" });
  234. }, activationRowSelector(pluginId));
  235. }
  236. async function clickActivationRow(pluginId: string): Promise<void> {
  237. const clicked = await browser.execute((selector) => {
  238. const row = document.querySelector<HTMLElement>(selector);
  239. row?.scrollIntoView({ block: "center" });
  240. row?.click();
  241. return Boolean(row);
  242. }, activationRowSelector(pluginId));
  243. if (!clicked) throw new Error(`the launcher has no activation row for ${pluginId}`);
  244. }
  245. async function readDialog(): Promise<string | null> {
  246. return browser.execute((id) => {
  247. const dialog = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  248. return dialog ? (dialog.innerText ?? "") : null;
  249. }, TID_EXTENSION_ACTIVATION_DIALOG);
  250. }
  251. async function waitForDialog(message: string): Promise<string> {
  252. let text: string | null = null;
  253. await browser.waitUntil(
  254. async () => {
  255. text = await readDialog();
  256. return Boolean(text);
  257. },
  258. { timeout: 15000, interval: 200, timeoutMsg: message },
  259. );
  260. return text!;
  261. }
  262. async function waitForDialogClosed(message: string): Promise<void> {
  263. await browser.waitUntil(async () => (await readDialog()) === null, {
  264. timeout: 15000,
  265. timeoutMsg: message,
  266. });
  267. }
  268. /** 点对话框里文字为 label 的按钮(取消按钮没有 testid,按文字找)。 */
  269. async function clickDialogButton(label: string): Promise<void> {
  270. const clicked = await browser.execute(
  271. (id, text) => {
  272. const button = Array.from(
  273. document.querySelectorAll<HTMLButtonElement>(`[data-testid="${id}"] button`),
  274. ).find((element) => (element.textContent ?? "").trim() === text);
  275. button?.click();
  276. return Boolean(button);
  277. },
  278. TID_EXTENSION_ACTIVATION_DIALOG,
  279. label,
  280. );
  281. if (!clicked) throw new Error(`the activation dialog has no button "${label}"`);
  282. }
  283. async function confirmDialog(): Promise<void> {
  284. await browser.execute(
  285. (id, confirmTestId) => {
  286. document
  287. .querySelector<HTMLElement>(`[data-testid="${id}"] [data-testid="${confirmTestId}"]`)
  288. ?.click();
  289. },
  290. TID_EXTENSION_ACTIVATION_DIALOG,
  291. TID_CONFIRM_DIALOG_CONFIRM,
  292. );
  293. await waitForDialogClosed("the activation dialog should close after confirming");
  294. }
  295. /** 经设置页进入插件商店,打开卡片并安装(安装即启用,user 层)。 */
  296. async function installFromStore(pluginId: string): Promise<void> {
  297. await openPluginSettings();
  298. await clickPluginControl("plugin-store-segment-personal");
  299. await openPluginCard(pluginId);
  300. await installPluginThroughUi(pluginId);
  301. await clickPluginControl("plugin-store-detail-back");
  302. await clickTestIdByDom("desktop-top-nav-back");
  303. }
  304. describe("PLM-EXT-P3B 扩展的会话读连接与商店安装后的激活确认", () => {
  305. after(async () => {
  306. evidence.screenshots = screenshots;
  307. await writeFile(
  308. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-p3b-evidence.json"),
  309. JSON.stringify(evidence, null, 2),
  310. ).catch(() => undefined);
  311. await restoreHandoffProbes().catch(() => undefined);
  312. await clearAppData();
  313. });
  314. it("列表、上限、实时行、readRows 与换代后的 reset", async function () {
  315. this.timeout(600000);
  316. requirePluginManualReview();
  317. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  318. await seedPlugin();
  319. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  320. afterElectronProcessExit: async () => {
  321. await seedSessions();
  322. await log.mark();
  323. },
  324. });
  325. await prepareV4ConversationE2E();
  326. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  327. // (a) 列表:订阅后的第一个事件是 snapshot,种子会话都在里面。
  328. evidence.listSnapshot = await log.waitFor(
  329. (line) =>
  330. line.includes("E2E_READS_LIST kind=snapshot") && line.includes(`seeds=${SEED_COUNT}`),
  331. "the list snapshot should contain the seeded sessions",
  332. 90000,
  333. );
  334. evidence.listPumpStarted = await log.waitFor(
  335. (line) => line.includes("[extensions]") && line.includes("session list pump started"),
  336. "the Window Host should start the session list pump",
  337. );
  338. // (b) 上限:同一插件 9 个不同会话,前 8 个收到 reset,第 9 个 limit-exceeded;之后全部退订。
  339. const limitLine = await log.waitFor(
  340. (line) => line.includes("E2E_READS_LIMIT results="),
  341. "the limit probe should finish",
  342. 180000,
  343. );
  344. evidence.limit = limitLine;
  345. const results = limitLine.split("results=")[1]!.trim().split(",");
  346. expect(results).toHaveLength(SEED_COUNT);
  347. expect(results.slice(0, 8).every((result) => result === "event:reset")).toBe(true);
  348. expect(results[8]).toBe("error:limit-exceeded");
  349. const connectionLine = await log.waitFor(
  350. (line) => line.includes("session read connection open connectionId=extension-host:"),
  351. "the Window Host should open the extension read connection",
  352. );
  353. evidence.readConnection = connectionLine;
  354. const gen = Number(/connectionId=extension-host:(\d+)/.exec(connectionLine)?.[1]);
  355. expect(gen).toBeGreaterThan(0);
  356. await log.waitFor(
  357. (line) => line.includes("E2E_READS_LIMIT released"),
  358. "the limit probe should release its subscriptions",
  359. );
  360. await browser.waitUntil(
  361. async () =>
  362. (await log.lines()).filter((line) => line.includes("session mirror released")).length >= 8,
  363. { timeout: 30000, timeoutMsg: "the Window Host should release the 8 probe mirrors" },
  364. );
  365. evidence.mirrorsSubscribed = (await log.lines()).filter((line) =>
  366. line.includes("session mirror subscribed"),
  367. ).length;
  368. // (c) 打开视图;在界面上发消息:视图实时出现用户行与助手回复,插件收到 rows 增量。
  369. await openLauncherView(LAUNCHER_ITEM);
  370. await waitForViewPane(
  371. VIEW_ID,
  372. (item) => item.phase === "running" && item.displayed,
  373. "the rows view should be running",
  374. );
  375. const beforeSend = (await log.lines()).length;
  376. await sendV4Prompt(PROMPT);
  377. const pane = await waitForV4Pane(
  378. (snapshot) => Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  379. "the draft should become a session after the first send",
  380. 60000,
  381. );
  382. const sessionId = pane.sessionId ?? "";
  383. evidence.sessionId = sessionId;
  384. await waitForV4AssistantMessageContaining(REPLY);
  385. const page = await waitForViewPage(
  386. VIEW_ID,
  387. (view) => view.text.includes(MARKER) && view.text.includes(REPLY),
  388. "the rows view should show the user row and the reply",
  389. 60000,
  390. );
  391. evidence.viewPage = page;
  392. expect(page.dataset.sessionId).toBe(sessionId);
  393. evidence.watch = await waitForLogAfter(
  394. beforeSend,
  395. (line) => line.includes(`E2E_READS_WATCH session=${sessionId}`),
  396. "the extension should watch the new session",
  397. );
  398. evidence.reset = await waitForLogAfter(
  399. beforeSend,
  400. (line) => line.includes(`E2E_READS_ROWS session=${sessionId} kind=reset`),
  401. "the first rows event should be reset",
  402. );
  403. evidence.liveRows = await waitForLogAfter(
  404. beforeSend,
  405. (line) =>
  406. line.includes(`E2E_READS_ROWS session=${sessionId} kind=rows`) &&
  407. line.includes("reply=true"),
  408. "the reply should arrive as a live rows event",
  409. );
  410. evidence.readRows = await waitForLogAfter(
  411. beforeSend,
  412. (line) => line.includes(`E2E_READS_READROWS session=${sessionId}`),
  413. "readRows should return the session rows",
  414. );
  415. expect(String(evidence.readRows)).toContain("marker=true");
  416. evidence.conversation = await waitForLogAfter(
  417. beforeSend,
  418. (line) => line.includes(`E2E_READS_CONV session=${sessionId} phase=`),
  419. "the extension should receive the conversation state",
  420. );
  421. // 行与会话状态都不记正文:日志里不能有提示词原文。
  422. const readLines = (await log.lines()).filter((line) => line.includes("E2E_READS_"));
  423. expect(JSON.stringify(readLines)).not.toContain("Reply with exactly");
  424. await capture("reads-view-zh-CN-zai-light");
  425. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  426. await waitForViewPage(
  427. VIEW_ID,
  428. (view) => view.text.includes(REPLY),
  429. "the rows view should stay after switching presentation",
  430. );
  431. await capture("reads-view-en-US-zai-dark");
  432. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  433. // (d) 杀掉扩展进程:新一代重新激活、重新订阅,第一个事件是 reset,镜像里有完整的行。
  434. const before = await readFixtureState();
  435. expect(before?.pid).toBeGreaterThan(0);
  436. const beforeKill = (await log.lines()).length;
  437. process.kill(before!.pid, "SIGKILL");
  438. await browser.waitUntil(async () => (await readFixtureState())?.pid !== before!.pid, {
  439. timeout: 60000,
  440. timeoutMsg: "the extension host should restart and re-activate the fixture",
  441. });
  442. evidence.resetAfterKill = await waitForLogAfter(
  443. beforeKill,
  444. (line) =>
  445. line.includes(`E2E_READS_ROWS session=${sessionId} kind=reset`) &&
  446. line.includes("marker=true") &&
  447. line.includes("reply=true"),
  448. "the new generation should start with a reset carrying the rows",
  449. );
  450. const reconnected = await waitForLogAfter(
  451. beforeKill,
  452. (line) => line.includes("session read connection open connectionId=extension-host:"),
  453. "the new generation should open its own read connection",
  454. );
  455. evidence.reconnected = reconnected;
  456. expect(Number(/connectionId=extension-host:(\d+)/.exec(reconnected)?.[1])).toBeGreaterThan(gen);
  457. evidence.closedOld = await waitForLogAfter(
  458. beforeKill,
  459. (line) => line.includes(`session read connection closed connectionId=extension-host:${gen}`),
  460. "the old generation's read connection should be released",
  461. );
  462. // (h) 「重新加载扩展」:扩展重新激活、重新订阅,这个会话的第一个行事件是 reset,带完整的行。
  463. // 宿主行为,以前只由示例插件用例 PLM-JARVIS-1 断言。
  464. const beforeReload = (await log.lines()).length;
  465. await reloadExtensionsFromCommandCenter();
  466. const firstAfterReload = await waitForLogAfter(
  467. beforeReload,
  468. (line) => line.includes(`E2E_READS_ROWS session=${sessionId} `),
  469. "the reloaded extension should subscribe to the session rows again",
  470. 90000,
  471. );
  472. evidence.firstRowsAfterReload = firstAfterReload;
  473. expect(firstAfterReload).toContain("kind=reset");
  474. expect(firstAfterReload).toContain("marker=true");
  475. expect(firstAfterReload).toContain("reply=true");
  476. // (i) 长历史:导入 40 轮的会话。行镜像只留尾部窗口(窗口里没有第一轮);扩展用
  477. // readRows({ beforeRowId }) 往前翻页,hasMore 直到翻到第一轮才变成 false。
  478. // 宿主行为,以前只由示例插件用例 PLM-JARVIS-1 断言。
  479. await installHandoffRpcProbe();
  480. const history = Array.from({ length: HISTORY_ROUNDS }, (_, index) => {
  481. const n = String(index + 1).padStart(3, "0");
  482. return [
  483. { role: "user", content: `E2E_READS_HISTORY_ASK_${n}` },
  484. { role: "assistant", content: `E2E_READS_HISTORY_REPLY_${n}` },
  485. ];
  486. }).flat();
  487. const beforeImport = (await log.lines()).length;
  488. const imported = await callHandoffHost<{ session: { sessionId: string } }>(
  489. ServiceChannels.ZCodeAgent,
  490. "createSession",
  491. [
  492. {
  493. workspacePath: DEFAULT_WORKSPACE,
  494. persistence: "immediate",
  495. importedHistory: { source: "claudeCode", title: "E2E_READS_HISTORY", messages: history },
  496. },
  497. ],
  498. );
  499. const historyId = imported.session.sessionId;
  500. const paged = await waitForLogAfter(
  501. beforeImport,
  502. (line) => line.includes(`E2E_READS_HISTORY session=${historyId} `),
  503. "the extension should page through the imported history",
  504. 90000,
  505. );
  506. evidence.historyPaging = paged;
  507. const field = (name: string) => new RegExp(`\\b${name}=(\\S+)`).exec(paged)?.[1];
  508. expect(field("windowHasFirst")).toBe("false");
  509. expect(field("hasFirst")).toBe("true");
  510. expect(field("hasMore")).toBe("false");
  511. expect(Number(field("pages"))).toBeGreaterThanOrEqual(2);
  512. expect(Number(field("total"))).toBeGreaterThan(Number(field("window")));
  513. expect(Number(field("total"))).toBeGreaterThanOrEqual(HISTORY_ROUNDS * 2);
  514. });
  515. it("商店安装的带代码扩展先不激活:不激活保持停用,确认后激活", async function () {
  516. this.timeout(600000);
  517. requirePluginManualReview();
  518. // 前一个用例的 e2e-ext-reads 持有 sessions.read:再从商店装带代码的插件要先确认。
  519. const market = join(fixturesDir(), "store-market");
  520. await cp(join(FIXTURE_ROOT, "store-market"), market, { recursive: true, force: true });
  521. await addMarketplaceSourceThroughAgent(market);
  522. await waitUntilPluginOverview(
  523. (overview) =>
  524. [STORE_A, STORE_B].every((id) =>
  525. overview.availablePlugins.some((plugin) => plugin.id === id),
  526. ),
  527. "the store fixture market should list both plugins",
  528. 60000,
  529. );
  530. // (a) 安装 A:Window Host 记为 pending,扩展进程不激活它;启动页显示「需要确认」。
  531. const beforeA = (await log.lines()).length;
  532. await installFromStore(STORE_A);
  533. evidence.heldA = await waitForLogAfter(
  534. beforeA,
  535. (line) => line.includes(`extension activation held plugin=${STORE_A}`),
  536. "the Window Host should hold the newly installed extension",
  537. );
  538. await browser.waitUntil(async () => (await activationOf(STORE_A)) === "pending", {
  539. timeout: 15000,
  540. timeoutMsg: "grants.json should record the pending activation",
  541. });
  542. await waitForVisibleActivationRow(
  543. STORE_A,
  544. "the launcher should show the needs-confirmation row",
  545. );
  546. evidence.rowA = await readActivationRow(STORE_A);
  547. expect(String(evidence.rowA)).toContain("需要确认");
  548. await capture("activation-row-zh-CN-zai-light");
  549. // (b) 对话框列出持有者;「不激活」→ declined,行消失,扩展代码不运行,技能照常。
  550. await clickActivationRow(STORE_A);
  551. evidence.dialogA = await waitForDialog("the activation row should open the dialog");
  552. expect(String(evidence.dialogA)).toContain("的扩展代码?");
  553. expect(String(evidence.dialogA)).toContain(PLUGIN);
  554. expect(String(evidence.dialogA)).toContain("不激活时,插件的技能与 MCP 照常可用。");
  555. await capture("activation-dialog-zh-CN-zai-light");
  556. await clickDialogButton("不激活");
  557. await waitForDialogClosed("the activation dialog should close after declining");
  558. await browser.waitUntil(async () => (await activationOf(STORE_A)) === "declined", {
  559. timeout: 15000,
  560. timeoutMsg: "grants.json should record the declined activation",
  561. });
  562. await browser.waitUntil(async () => (await readActivationRow(STORE_A)) === null, {
  563. timeout: 15000,
  564. timeoutMsg: "the needs-confirmation row should disappear after declining",
  565. });
  566. const pluginA = (await getPluginList()).plugins.find((plugin) => plugin.id === STORE_A);
  567. evidence.pluginA = pluginA ? { id: pluginA.id, enabled: pluginA.enabled } : null;
  568. expect(pluginA?.enabled).toBe(true);
  569. const catalogA = (await getPluginReferenceCatalog()).plugins.find(
  570. (plugin) => plugin.pluginId === STORE_A,
  571. );
  572. evidence.catalogA = catalogA
  573. ? { enabled: catalogA.enabled, skills: catalogA.skillQualifiedNames }
  574. : null;
  575. expect(catalogA?.skillQualifiedNames.join(",")).toContain("e2e-store-skill-a");
  576. // (c) 安装 B:关闭对话框(Esc)不算决定,行还在;确认后扩展进程激活它。
  577. const beforeB = (await log.lines()).length;
  578. await installFromStore(STORE_B);
  579. await waitForLogAfter(
  580. beforeB,
  581. (line) => line.includes(`extension activation held plugin=${STORE_B}`),
  582. "the Window Host should hold the second extension",
  583. );
  584. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  585. await waitForVisibleActivationRow(STORE_B, "the launcher should show the row for B");
  586. evidence.rowB = await readActivationRow(STORE_B);
  587. expect(String(evidence.rowB)).toContain("Needs confirmation");
  588. await capture("activation-row-en-US-zai-dark");
  589. await clickActivationRow(STORE_B);
  590. evidence.dialogB = await waitForDialog("the activation row for B should open the dialog");
  591. expect(String(evidence.dialogB)).toContain("Activate the extension code of");
  592. await capture("activation-dialog-en-US-zai-dark");
  593. await browser.keys("Escape");
  594. await waitForDialogClosed("the activation dialog should close on Escape");
  595. expect(await activationOf(STORE_B)).toBe("pending");
  596. await waitForVisibleActivationRow(STORE_B, "the row should stay after dismissing the dialog");
  597. await clickActivationRow(STORE_B);
  598. await waitForDialog("the activation dialog should open again");
  599. const beforeAllow = (await log.lines()).length;
  600. await confirmDialog();
  601. evidence.activatedB = await waitForLogAfter(
  602. beforeAllow,
  603. (line) => line.includes(`E2E_STORE_ACTIVATED plugin=${STORE_B}`),
  604. "the extension host should activate B after confirming",
  605. );
  606. await browser.waitUntil(async () => (await activationOf(STORE_B)) === null, {
  607. timeout: 15000,
  608. timeoutMsg: "grants.json should drop the activation record after confirming",
  609. });
  610. await browser.waitUntil(async () => (await readActivationRow(STORE_B)) === null, {
  611. timeout: 15000,
  612. timeoutMsg: "the needs-confirmation row should disappear after confirming",
  613. });
  614. // A 一直没有激活。
  615. const activatedA = (await log.lines()).filter((line) =>
  616. line.includes(`E2E_STORE_ACTIVATED plugin=${STORE_A}`),
  617. );
  618. evidence.activatedA = activatedA;
  619. expect(activatedA).toEqual([]);
  620. evidence.grantsFile = await readGrantsFile();
  621. });
  622. });