plugin-extension-jarvis-host.test.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. // PLM-EXT-JARVISHOST:Jarvis 要的宿主能力(docs/plugins/extension-host.md §18.1、§18.4 Jarvis 第 1 步)。
  2. // 隔离 HOME:纯 JS fixture 扩展 e2e-ext-jarvis-host(test/e2e/fixtures/fs/plugins/plugin-extension-jarvis-host/)
  3. // 经 plugins.dirs 加载。发送消息走 replay(common.json 与 plugin-extension-jarvis-host.json 的 plugin-extension-jarvis-host-1)。
  4. // a H5 视图的 App 作用域:从 nav.primary 打开 scope "app" 的视图;切到同一工作区的另一个会话、再切回后实例 id 不变;
  5. // 全局「新建任务」进另一个工作区、再切回原会话的工作区,实例 id 仍不变,页面上只有一个这个视图的标签。
  6. // 新建任务会进新的虚拟工作区(另一个侧栏,标签不在那里),所以第二个会话经 Host 的 createSession(导入历史,
  7. // 不调模型)建在同一工作区,再从任务列表切换。
  8. // b H6 ctx.extension.dataPath:等于 CLI 的插件数据目录(<E2E HOME>/.zcode/cli/plugins/data/<插件 id>),激活前已建好。
  9. // c H9 models.list:列出 E2E provider 的模型,标签就是模型 id。
  10. // d H11 导航未读标记:激活时为 3;经视图工具改成 120(显示 99+)、"dot"、清除。
  11. // e H12 grants.request:视图工具请宿主弹授权对话框;取消后返回空档位,确认后返回 sessions.read,再请求不弹。
  12. // f H8 notifications.show:Main 的 Notification.show 换成记录、窗口焦点换成受控读数(测试机上不弹真实通知)。
  13. // 依次:窗口有焦点 → focused;设置里「任务通知」关 → disabled;详情页开关关 → muted;都放开 → 弹出,
  14. // 标题带插件名前缀;紧接着第二条 → rate-limited;触发记录的通知的 click → 打开该插件的视图。
  15. // 运行时证据:Main 日志([extension-host] / [extensions] 前缀与 fixture 写的 E2E_JARVISHOST_*)、视图标签页与页面 DOM。
  16. import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
  17. import { join, resolve } from "node:path";
  18. import { ServiceChannels } from "@zcode/shared";
  19. import {
  20. TID_CONFIRM_DIALOG_CONFIRM,
  21. TID_EXTENSION_GRANT_DIALOG,
  22. TID_EXTENSION_PERMISSIONS,
  23. TID_EXTENSION_PERMISSIONS_ACTION,
  24. TID_EXTENSION_PERMISSIONS_NOTIFICATIONS,
  25. TID_NAV_PRIMARY_ITEM,
  26. TID_SETTINGS_BACK_BUTTON,
  27. TID_SETTINGS_PAGE,
  28. TID_SETTINGS_SECTION_NAV,
  29. TID_TASK_NEW_BUTTON,
  30. TID_TASK_SETTINGS_BUTTON,
  31. testId,
  32. } from "@zcode/shared/test-ids";
  33. import {
  34. DEFAULT_WORKSPACE,
  35. clearAppData,
  36. clickTestIdByDom,
  37. getE2EAppDataPaths,
  38. setCurrentElectronRendererContentSize,
  39. waitForTestIdByDom,
  40. } from "#e2e/helpers/desktop-app";
  41. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  42. import { callHandoffHost, installHandoffRpcProbe } from "#e2e/helpers/remote-project-handoff-probe";
  43. import {
  44. UPSTREAM_MODEL,
  45. UPSTREAM_PROVIDER_ID,
  46. UPSTREAM_SECONDARY_MODEL,
  47. } from "#e2e/helpers/upstream-provider";
  48. import {
  49. createExtensionLog,
  50. evaluateInViewPage,
  51. openLauncher,
  52. readActiveSidePaneTab,
  53. reloadExtensionsFromCommandCenter,
  54. waitForViewPage,
  55. waitForViewPane,
  56. writePluginDirsConfig,
  57. } from "#e2e/helpers/extension-host-views";
  58. import {
  59. prepareV4ConversationE2E,
  60. selectV4TaskById,
  61. sendV4Prompt,
  62. waitForV4AssistantMessageContaining,
  63. waitForV4Pane,
  64. } from "#e2e/helpers/v4-conversation";
  65. import {
  66. capturePluginManualReview,
  67. openInstalledPluginSettingsDetail,
  68. openPluginManagementSettings,
  69. requirePluginManualReview,
  70. setPluginPresentation,
  71. } from "#e2e/helpers/plugin-management-lifecycle";
  72. const CASE_ID = "PLM-EXT-JARVISHOST";
  73. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  74. const FIXTURE_ROOT = resolve(
  75. process.cwd(),
  76. "test/e2e/fixtures/fs/plugins/plugin-extension-jarvis-host",
  77. );
  78. const PLUGIN = "e2e-ext-jarvis-host";
  79. const PLUGIN_ID = `${PLUGIN}@inline`;
  80. const HOME_VIEW = `${PLUGIN_ID}/home`;
  81. const NAV_ITEM = `${PLUGIN_ID}/home`;
  82. const PROMPT = `E2E_EXT_JARVIS_HOST: Reply with exactly "upstream-e2e-ok" and no other text.`;
  83. /** 当前工作区路径(Renderer 的标签 store)。 */
  84. async function readActiveWorkspacePath(): Promise<string | null> {
  85. return browser.execute(
  86. () =>
  87. (
  88. window as Window & {
  89. __zcodeTabStoreE2E?: { getState(): { activeWorkspacePath?: string | null } };
  90. }
  91. ).__zcodeTabStoreE2E?.getState().activeWorkspacePath ?? null,
  92. );
  93. }
  94. const evidence: Record<string, unknown> = {};
  95. const log = createExtensionLog();
  96. function fixtureHome(): string {
  97. return join(getE2EAppDataPaths().homeDir, "fixtures", "extension-jarvis-host");
  98. }
  99. /** fixture 激活时写下的扩展进程 pid(插件目录旁的状态文件)。 */
  100. async function readFixturePid(): Promise<number | null> {
  101. return readFile(join(fixtureHome(), "e2e-ext-jarvis-host-state.json"), "utf8").then(
  102. (text) => Number((JSON.parse(text) as { pid?: number }).pid) || null,
  103. () => null,
  104. );
  105. }
  106. /** 最近一行 E2E_JARVISHOST_DATA 的 previous 与 count。 */
  107. function parseDataLine(line: string): { previous: number; count: number } {
  108. return {
  109. previous: Number(/previous=(\d+)/.exec(line)?.[1]),
  110. count: Number(/count=(\d+)/.exec(line)?.[1]),
  111. };
  112. }
  113. async function seedFixture(): Promise<void> {
  114. const target = fixtureHome();
  115. await mkdir(target, { recursive: true });
  116. await cp(join(FIXTURE_ROOT, PLUGIN), join(target, PLUGIN), { recursive: true, force: true });
  117. await writePluginDirsConfig([join(target, PLUGIN)], [PLUGIN_ID]);
  118. }
  119. async function clickNavItem(itemId: string): Promise<void> {
  120. await browser.waitUntil(
  121. async () =>
  122. browser.execute(
  123. (itemTestId, id) => {
  124. const element = document.querySelector<HTMLElement>(
  125. `[data-testid="${itemTestId}"][data-extension-item="${id}"]`,
  126. );
  127. if (!element) return false;
  128. element.click();
  129. return true;
  130. },
  131. TID_NAV_PRIMARY_ITEM,
  132. itemId,
  133. ),
  134. { timeout: 30000, interval: 300, timeoutMsg: `nav item ${itemId} should be clickable` },
  135. );
  136. }
  137. interface NavBadgeReading {
  138. badge: string;
  139. label: string;
  140. text: string;
  141. hasDot: boolean;
  142. }
  143. async function readNavBadge(itemId: string): Promise<NavBadgeReading | null> {
  144. return browser.execute(
  145. (itemTestId, id) => {
  146. const element = document.querySelector<HTMLElement>(
  147. `[data-testid="${itemTestId}"][data-extension-item="${id}"]`,
  148. );
  149. if (!element) return null;
  150. return {
  151. badge: element.dataset.extensionBadge ?? "",
  152. label: element.getAttribute("aria-label") ?? "",
  153. text: element.textContent ?? "",
  154. hasDot: Boolean(element.querySelector(".bg-icon-blue")),
  155. };
  156. },
  157. TID_NAV_PRIMARY_ITEM,
  158. itemId,
  159. );
  160. }
  161. async function waitForNavBadge(
  162. itemId: string,
  163. predicate: (reading: NavBadgeReading) => boolean,
  164. message: string,
  165. ): Promise<NavBadgeReading> {
  166. let reading: NavBadgeReading | null = null;
  167. await browser.waitUntil(
  168. async () => {
  169. reading = await readNavBadge(itemId);
  170. return Boolean(reading && predicate(reading));
  171. },
  172. { timeout: 30000, interval: 300, timeoutMsg: `${message}: ${JSON.stringify(reading)}` },
  173. );
  174. return reading!;
  175. }
  176. /**
  177. * 在视图页面里调视图工具(页面经 window.zcode 调,与插件页面相同的路径)。
  178. * wait 为 false 时不等结果:grants.request 要等对话框关闭才返回。
  179. */
  180. async function callViewTool(
  181. sandboxId: string,
  182. name: string,
  183. args: unknown,
  184. wait = true,
  185. ): Promise<void> {
  186. const call = `window.zcode.callTool(${JSON.stringify(name)}, ${JSON.stringify(args)})`;
  187. await evaluateInViewPage(sandboxId, wait ? `${call}.then(() => true)` : `(void ${call}, true)`);
  188. }
  189. /** ConfirmDialog 的内容层(按 testId)。 */
  190. async function readDialog(dialogTestId: string): Promise<string | null> {
  191. return browser.execute((id) => {
  192. const dialog = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  193. return dialog ? (dialog.innerText ?? "") : null;
  194. }, dialogTestId);
  195. }
  196. async function waitForDialog(dialogTestId: string, message: string): Promise<string> {
  197. let text: string | null = null;
  198. await browser.waitUntil(
  199. async () => {
  200. text = await readDialog(dialogTestId);
  201. return Boolean(text);
  202. },
  203. { timeout: 15000, interval: 200, timeoutMsg: message },
  204. );
  205. return text!;
  206. }
  207. async function closeDialog(dialogTestId: string, confirm: boolean): Promise<void> {
  208. if (confirm) {
  209. await browser.execute(
  210. (id, confirmTestId) => {
  211. document
  212. .querySelector<HTMLElement>(`[data-testid="${id}"] [data-testid="${confirmTestId}"]`)
  213. ?.click();
  214. },
  215. dialogTestId,
  216. TID_CONFIRM_DIALOG_CONFIRM,
  217. );
  218. } else {
  219. await browser.keys("Escape");
  220. }
  221. await browser.waitUntil(async () => (await readDialog(dialogTestId)) === null, {
  222. timeout: 15000,
  223. timeoutMsg: `${dialogTestId} should close`,
  224. });
  225. }
  226. // —— H8:Main 里的通知记录与焦点读数 ——
  227. interface RecordedNotification {
  228. title: string;
  229. body: string;
  230. silent: boolean;
  231. }
  232. /** 把 Main 的 Notification.show 换成记录,窗口焦点读数改成受控(focused 为 null 时用真实值)。 */
  233. async function installMainNotificationProbe(): Promise<void> {
  234. await browser.electron.execute((electron) => {
  235. const scope = globalThis as typeof globalThis & {
  236. __e2eExtNotifications?: Array<InstanceType<typeof electron.Notification>>;
  237. __e2eFocusOverride?: boolean | null;
  238. __e2eRestoreNotificationProbe?: () => void;
  239. };
  240. if (scope.__e2eRestoreNotificationProbe) return;
  241. scope.__e2eExtNotifications = [];
  242. scope.__e2eFocusOverride = null;
  243. const notificationProto = electron.Notification.prototype;
  244. const windowProto = electron.BrowserWindow.prototype;
  245. const originalShow = notificationProto.show;
  246. const originalFocused = windowProto.isFocused;
  247. notificationProto.show = function () {
  248. scope.__e2eExtNotifications!.push(this);
  249. };
  250. windowProto.isFocused = function () {
  251. return scope.__e2eFocusOverride ?? originalFocused.call(this);
  252. };
  253. scope.__e2eRestoreNotificationProbe = () => {
  254. notificationProto.show = originalShow;
  255. windowProto.isFocused = originalFocused;
  256. delete scope.__e2eRestoreNotificationProbe;
  257. };
  258. });
  259. }
  260. async function setMainFocus(focused: boolean | null): Promise<void> {
  261. await browser.electron.execute((_electron, value) => {
  262. (globalThis as typeof globalThis & { __e2eFocusOverride?: boolean | null }).__e2eFocusOverride =
  263. value;
  264. }, focused);
  265. }
  266. async function readRecordedNotifications(): Promise<RecordedNotification[]> {
  267. return browser.electron.execute(() =>
  268. (
  269. (
  270. globalThis as typeof globalThis & {
  271. __e2eExtNotifications?: Array<{ title: string; body: string; silent: boolean }>;
  272. }
  273. ).__e2eExtNotifications ?? []
  274. ).map((item) => ({ title: item.title, body: item.body, silent: item.silent })),
  275. );
  276. }
  277. async function clickRecordedNotification(index: number): Promise<void> {
  278. await browser.electron.execute((_electron, at) => {
  279. (
  280. globalThis as typeof globalThis & {
  281. __e2eExtNotifications?: Array<{ emit(event: string): void }>;
  282. }
  283. ).__e2eExtNotifications?.[at]?.emit("click");
  284. }, index);
  285. }
  286. async function restoreMainNotificationProbe(): Promise<void> {
  287. await browser.electron
  288. .execute(() => {
  289. (
  290. globalThis as typeof globalThis & { __e2eRestoreNotificationProbe?: () => void }
  291. ).__e2eRestoreNotificationProbe?.();
  292. })
  293. .catch(() => undefined);
  294. }
  295. /** 打开设置页的一个分区。 */
  296. async function openSettingsSection(section: string): Promise<void> {
  297. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  298. timeout: 15000,
  299. timeoutMsg: "the settings button should be visible",
  300. });
  301. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 15000 });
  302. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, section), {
  303. timeout: 15000,
  304. timeoutMsg: `settings should expose the ${section} section`,
  305. });
  306. }
  307. async function closeSettings(): Promise<void> {
  308. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  309. timeout: 15000,
  310. timeoutMsg: "the settings back button should be visible",
  311. });
  312. }
  313. /** 设置页「任务通知」一行的开关(全局的系统通知开关):设成 checked。 */
  314. async function setTaskNotificationSwitch(checked: boolean): Promise<void> {
  315. await browser.waitUntil(
  316. async () =>
  317. browser.execute((wanted) => {
  318. const label = Array.from(document.querySelectorAll<HTMLElement>("body *")).find(
  319. (element) =>
  320. element.childElementCount === 0 &&
  321. /^(任务通知|Task notifications)$/.test(element.textContent?.trim() ?? ""),
  322. );
  323. let row: HTMLElement | null = label ?? null;
  324. let control: HTMLElement | null = null;
  325. while (row && !control) {
  326. control = row.querySelector<HTMLElement>('[role="switch"]');
  327. row = row.parentElement;
  328. }
  329. if (!control) return false;
  330. if ((control.getAttribute("aria-checked") === "true") !== wanted) control.click();
  331. return (control.getAttribute("aria-checked") === "true") === wanted;
  332. }, checked),
  333. {
  334. timeout: 15000,
  335. interval: 300,
  336. timeoutMsg: `the task notification switch should be ${checked}`,
  337. },
  338. );
  339. }
  340. async function readNotificationsSwitch(pluginId: string): Promise<boolean | null> {
  341. return browser.execute(
  342. (switchTestId, id) => {
  343. const element = document.querySelector<HTMLElement>(
  344. `[data-testid="${switchTestId}"][data-plugin-id="${id}"]`,
  345. );
  346. return element ? element.getAttribute("aria-checked") === "true" : null;
  347. },
  348. TID_EXTENSION_PERMISSIONS_NOTIFICATIONS,
  349. pluginId,
  350. );
  351. }
  352. async function readPermissionActions(pluginId: string): Promise<string[]> {
  353. return browser.execute(
  354. (sectionTestId, actionTestId, id) =>
  355. Array.from(
  356. document.querySelectorAll<HTMLElement>(
  357. `[data-testid="${sectionTestId}"][data-plugin-id="${id}"] [data-testid="${actionTestId}"]`,
  358. ),
  359. ).map((row) => row.dataset.capability ?? ""),
  360. TID_EXTENSION_PERMISSIONS,
  361. TID_EXTENSION_PERMISSIONS_ACTION,
  362. pluginId,
  363. );
  364. }
  365. describe("PLM-EXT-JARVISHOST Jarvis 要的宿主能力", () => {
  366. after(async () => {
  367. await writeFile(
  368. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-jarvishost-evidence.json"),
  369. JSON.stringify(evidence, null, 2),
  370. ).catch(() => undefined);
  371. await restoreMainNotificationProbe();
  372. await clearAppData();
  373. });
  374. it("App 作用域视图、数据目录与模型列表", async function () {
  375. this.timeout(600000);
  376. requirePluginManualReview();
  377. expect(process.env.E2E_PROVIDER_CAPTURE_MODE).toBe("replay");
  378. await seedFixture();
  379. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  380. afterElectronProcessExit: () => log.mark(),
  381. });
  382. await prepareV4ConversationE2E();
  383. await setCurrentElectronRendererContentSize(1400, 900);
  384. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  385. await log.waitFor(
  386. (line) => line.includes(`[${PLUGIN_ID}] activated in`),
  387. "the fixture extension should activate",
  388. 60000,
  389. );
  390. // (b) H6:数据目录来自 CLI 的 plugins/list,激活前已存在。
  391. const dataLine = await log.waitFor(
  392. (line) => line.includes("E2E_JARVISHOST_DATAPATH "),
  393. "the fixture should report its data path",
  394. );
  395. const reported = JSON.parse(
  396. dataLine.slice(dataLine.indexOf("{", dataLine.indexOf("E2E_JARVISHOST_DATAPATH"))),
  397. ) as {
  398. dataPath: string;
  399. isDirectory: boolean;
  400. };
  401. evidence.dataPath = reported;
  402. expect(reported.dataPath).toBe(
  403. join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "plugins", "data", PLUGIN_ID),
  404. );
  405. expect(reported.isDirectory).toBe(true);
  406. // (c) H9:已配置的模型,与输入框模型选择器同一份视图。
  407. const modelsLine = await log.waitFor(
  408. (line) => line.includes("E2E_JARVISHOST_MODELS "),
  409. "the fixture should report models.list",
  410. 60000,
  411. );
  412. expect(modelsLine).toContain("E2E_JARVISHOST_MODELS ok ");
  413. const okMarker = "E2E_JARVISHOST_MODELS ok ";
  414. const models = JSON.parse(
  415. modelsLine.slice(modelsLine.indexOf(okMarker) + okMarker.length),
  416. ) as Array<{
  417. id: string;
  418. providerId: string;
  419. modelId: string;
  420. label: string;
  421. providerName: string;
  422. }>;
  423. evidence.models = models;
  424. expect(models.length).toBeGreaterThan(0);
  425. expect(models.map((model) => model.id)).toContain(`${UPSTREAM_PROVIDER_ID}/${UPSTREAM_MODEL}`);
  426. // 已配置的第二个模型也在列表里(以前只由示例插件用例 PLM-JARVIS-2 断言)。
  427. expect(models.map((model) => model.id)).toContain(
  428. `${UPSTREAM_PROVIDER_ID}/${UPSTREAM_SECONDARY_MODEL}`,
  429. );
  430. for (const model of models) {
  431. expect(model.id).toBe(`${model.providerId}/${model.modelId}`);
  432. expect(model.label).toBe(model.modelId);
  433. expect(model.providerName.length).toBeGreaterThan(0);
  434. }
  435. // (a) H5:先发一条消息建正式会话,再从导航打开 App 作用域的视图。
  436. await sendV4Prompt(PROMPT);
  437. const session = await waitForV4Pane(
  438. (snapshot) => Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  439. "the draft should become a session after the first send",
  440. 60000,
  441. );
  442. const sessionId = session.sessionId ?? "";
  443. evidence.sessionId = sessionId;
  444. await waitForV4AssistantMessageContaining("deepseek-e2e-ok");
  445. await clickNavItem(NAV_ITEM);
  446. const pane = await waitForViewPane(
  447. HOME_VIEW,
  448. (item) => item.phase === "running" && item.displayed,
  449. "the app-scoped view should be running",
  450. );
  451. evidence.appPane = pane;
  452. expect(pane.scope).toBe("app");
  453. const page = await waitForViewPage(
  454. HOME_VIEW,
  455. (item) => item.dataset.ready === "1",
  456. "the app-scoped view page should render",
  457. );
  458. evidence.appPage = page.dataset;
  459. expect(page.dataset.scope).toBe("app");
  460. expect(page.dataset.instance).toBe(pane.instance);
  461. const opened = await log.waitFor(
  462. (line) => line.includes(`E2E_JARVISHOST_VIEW_OPEN instance=${pane.instance}`),
  463. "onDidOpen should run for the app-scoped view",
  464. );
  465. expect(opened).toContain("scope=app session=none");
  466. await capturePluginManualReview(CASE_ID, "app-view-zh-CN-zai-light");
  467. // 同一工作区的第二个会话:导入历史建会话,不调模型;从任务列表切过去,焦点会话变了,实例不重建。
  468. await installHandoffRpcProbe();
  469. const workspace = await browser.execute(() => {
  470. const tabs = (
  471. window as Window & {
  472. __zcodeTabStoreE2E?: {
  473. getState(): {
  474. activeWorkspacePath: string | null;
  475. activeWorkspaceIdentity: string | null;
  476. };
  477. };
  478. }
  479. ).__zcodeTabStoreE2E!.getState();
  480. return { path: tabs.activeWorkspacePath!, identity: tabs.activeWorkspaceIdentity };
  481. });
  482. const created = await callHandoffHost<{ session: { sessionId: string } }>(
  483. ServiceChannels.ZCodeAgent,
  484. "createSession",
  485. [
  486. {
  487. workspacePath: workspace.path,
  488. ...(workspace.identity ? { workspaceIdentity: workspace.identity } : {}),
  489. persistence: "immediate",
  490. importedHistory: {
  491. source: "claudeCode",
  492. title: "E2E_JARVISHOST_SECOND_SESSION",
  493. messages: [
  494. { role: "user", content: "E2E_JARVISHOST_SECOND_SESSION" },
  495. { role: "assistant", content: "second session for the app-scoped view check" },
  496. ],
  497. },
  498. },
  499. ],
  500. );
  501. const secondSessionId = created.session.sessionId;
  502. evidence.secondSessionId = secondSessionId;
  503. await callHandoffHost(ServiceChannels.ZCodeTask, "resumeTask", [
  504. { taskId: secondSessionId, workspacePath: workspace.path },
  505. ]);
  506. await selectV4TaskById(secondSessionId, 30000);
  507. await browser.pause(1500);
  508. const afterSecond = await waitForViewPane(
  509. HOME_VIEW,
  510. (item) => item.phase === "running",
  511. "the app-scoped view should stay after switching to another session",
  512. );
  513. evidence.afterSecond = afterSecond;
  514. expect(afterSecond.instance).toBe(pane.instance);
  515. // 切回原会话:实例仍不变。
  516. await selectV4TaskById(sessionId);
  517. await waitForV4Pane((snapshot) => snapshot.sessionId === sessionId, "back to the session");
  518. await browser.pause(1500);
  519. const afterSwitch = await waitForViewPane(
  520. HOME_VIEW,
  521. (item) => item.phase === "running",
  522. "the app-scoped view should stay after switching sessions",
  523. );
  524. evidence.afterSwitch = afterSwitch;
  525. expect(afterSwitch.instance).toBe(pane.instance);
  526. // 切换工作区(§18.1 H5「跨工作区保留」):全局「新建任务」进一个新的虚拟工作区,标签跟着移过去,实例不重建;
  527. // 再从任务列表切回原会话(回到原工作区),实例仍不变。
  528. await clickTestIdByDom(TID_TASK_NEW_BUTTON, {
  529. timeout: 15000,
  530. timeoutMsg: "the global new task button should be visible",
  531. });
  532. let otherWorkspace = "";
  533. await browser.waitUntil(
  534. async () => {
  535. otherWorkspace = (await readActiveWorkspacePath()) ?? "";
  536. return Boolean(otherWorkspace) && otherWorkspace !== workspace.path;
  537. },
  538. { timeout: 30000, timeoutMsg: "the global new task should enter another workspace" },
  539. );
  540. evidence.otherWorkspace = otherWorkspace;
  541. await browser.pause(1500);
  542. const afterWorkspace = await waitForViewPane(
  543. HOME_VIEW,
  544. (item) => item.phase === "running",
  545. "the app-scoped view should move to the other workspace",
  546. );
  547. evidence.afterWorkspace = afterWorkspace;
  548. expect(afterWorkspace.instance).toBe(pane.instance);
  549. await selectV4TaskById(sessionId);
  550. await browser.waitUntil(async () => (await readActiveWorkspacePath()) === workspace.path, {
  551. timeout: 30000,
  552. timeoutMsg: "selecting the first session should return to its workspace",
  553. });
  554. await waitForV4Pane((snapshot) => snapshot.sessionId === sessionId, "back to the session");
  555. await browser.pause(1500);
  556. const afterWorkspaceBack = await waitForViewPane(
  557. HOME_VIEW,
  558. (item) => item.phase === "running" && item.displayed,
  559. "the app-scoped view should come back with the first workspace",
  560. );
  561. evidence.afterWorkspaceBack = afterWorkspaceBack;
  562. expect(afterWorkspaceBack.instance).toBe(pane.instance);
  563. // 标签只在当前工作区的侧栏里:页面上只有一个这个视图的标签。
  564. const paneCount = await browser.execute(
  565. (viewId) => document.querySelectorAll(`[data-extension-view-id="${viewId}"]`).length,
  566. HOME_VIEW,
  567. );
  568. evidence.paneCountAfterWorkspaceBack = paneCount;
  569. expect(paneCount).toBe(1);
  570. const opens = (await log.lines()).filter((line) => line.includes("E2E_JARVISHOST_VIEW_OPEN"));
  571. evidence.viewOpens = opens;
  572. expect(opens).toHaveLength(1);
  573. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  574. await capturePluginManualReview(CASE_ID, "app-view-en-US-zai-dark");
  575. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  576. // (d) H11:导航条目的未读标记。激活时扩展设为 3。
  577. const initialBadge = await waitForNavBadge(
  578. NAV_ITEM,
  579. (reading) => reading.badge === "3",
  580. "the nav item should show the badge set on activation",
  581. );
  582. evidence.initialBadge = initialBadge;
  583. expect(initialBadge.text).toContain("3");
  584. expect(initialBadge.label).toContain("3 条未读");
  585. const sandbox = afterSwitch.sandbox ?? "";
  586. await callViewTool(sandbox, "setBadge", { badge: 120 });
  587. const cappedBadge = await waitForNavBadge(
  588. NAV_ITEM,
  589. (reading) => reading.badge === "120",
  590. "the nav badge should update to 120",
  591. );
  592. expect(cappedBadge.text).toContain("99+");
  593. await callViewTool(sandbox, "setBadge", { badge: "dot" });
  594. const dotBadge = await waitForNavBadge(
  595. NAV_ITEM,
  596. (reading) => reading.badge === "dot",
  597. "the nav badge should become a dot",
  598. );
  599. evidence.dotBadge = dotBadge;
  600. expect(dotBadge.hasDot).toBe(true);
  601. expect(dotBadge.label).toContain("有新内容");
  602. await capturePluginManualReview(CASE_ID, "nav-badge-dot-zh-CN-zai-light");
  603. await callViewTool(sandbox, "setBadge", { badge: 5 });
  604. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  605. const englishBadge = await waitForNavBadge(
  606. NAV_ITEM,
  607. (reading) => reading.badge === "5" && reading.label.includes("5 unread"),
  608. "the nav badge should be localized",
  609. );
  610. evidence.englishBadge = englishBadge;
  611. await capturePluginManualReview(CASE_ID, "nav-badge-count-en-US-zai-dark");
  612. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  613. await callViewTool(sandbox, "setBadge", { badge: null });
  614. const cleared = await waitForNavBadge(
  615. NAV_ITEM,
  616. (reading) => reading.badge === "",
  617. "the nav badge should clear",
  618. );
  619. expect(cleared.hasDot).toBe(false);
  620. expect(cleared.label).not.toContain("·");
  621. // (e) H12:视图请宿主弹授权对话框。取消不是错误,返回空档位。
  622. const grantLines = async () =>
  623. (await log.lines()).filter((line) => line.includes("E2E_JARVISHOST_GRANTS "));
  624. await callViewTool(sandbox, "requestGrants", {}, false);
  625. const dialogText = await waitForDialog(
  626. TID_EXTENSION_GRANT_DIALOG,
  627. "grants.request should open the consent dialog",
  628. );
  629. evidence.grantDialog = dialogText;
  630. expect(dialogText).toContain(`允许「${PLUGIN}」读取会话?`);
  631. await capturePluginManualReview(CASE_ID, "grants-request-dialog-zh-CN-zai-light");
  632. await closeDialog(TID_EXTENSION_GRANT_DIALOG, false);
  633. await browser.waitUntil(async () => (await grantLines()).length === 1, {
  634. timeout: 15000,
  635. timeoutMsg: "grants.request should return after cancelling",
  636. });
  637. expect((await grantLines())[0]).toContain("E2E_JARVISHOST_GRANTS ok granted=");
  638. expect((await grantLines())[0]).not.toContain("sessions.read");
  639. // 确认:返回 sessions.read。
  640. await callViewTool(sandbox, "requestGrants", {}, false);
  641. await waitForDialog(TID_EXTENSION_GRANT_DIALOG, "grants.request should ask again");
  642. await closeDialog(TID_EXTENSION_GRANT_DIALOG, true);
  643. await browser.waitUntil(async () => (await grantLines()).length === 2, {
  644. timeout: 15000,
  645. timeoutMsg: "grants.request should return after granting",
  646. });
  647. expect((await grantLines())[1]).toContain("E2E_JARVISHOST_GRANTS ok granted=sessions.read");
  648. // 已授予:不弹对话框,直接返回。
  649. await callViewTool(sandbox, "requestGrants", {});
  650. await browser.waitUntil(async () => (await grantLines()).length === 3, {
  651. timeout: 15000,
  652. timeoutMsg: "grants.request should return at once when already granted",
  653. });
  654. expect((await grantLines())[2]).toContain("E2E_JARVISHOST_GRANTS ok granted=sessions.read");
  655. expect(await readDialog(TID_EXTENSION_GRANT_DIALOG)).toBeNull();
  656. evidence.grantResults = await grantLines();
  657. evidence.grantRelayLog = (await log.lines()).filter((line) => line.includes("grants.request"));
  658. expect(dialogText).toContain("系统通知");
  659. expect((await grantLines())[1]).toContain("granted=sessions.read,notifications");
  660. // (f) H8:系统通知。每次经视图工具 notify 调 notifications.show,读日志里的结果。
  661. await installMainNotificationProbe();
  662. const notifyResults = async () =>
  663. (await log.lines()).filter((line) => line.includes("E2E_JARVISHOST_NOTIFY "));
  664. const notify = async (args: Record<string, unknown>) => {
  665. const before = (await notifyResults()).length;
  666. const current = await waitForViewPane(
  667. HOME_VIEW,
  668. (item) => item.phase === "running" && Boolean(item.sandbox),
  669. "the view should be running before notify",
  670. );
  671. await waitForViewPage(HOME_VIEW, (item) => item.dataset.ready === "1", "view page ready");
  672. await callViewTool(current.sandbox ?? "", "notify", args);
  673. await browser.waitUntil(async () => (await notifyResults()).length > before, {
  674. timeout: 15000,
  675. timeoutMsg: "notifications.show should return",
  676. });
  677. return (await notifyResults()).at(-1)!;
  678. };
  679. // 窗口有焦点:不弹。
  680. await setMainFocus(true);
  681. expect(await notify({})).toContain(
  682. 'E2E_JARVISHOST_NOTIFY ok {"shown":false,"reason":"focused"}',
  683. );
  684. await setMainFocus(false);
  685. // 设置里「任务通知」关:不弹。
  686. await openSettingsSection("general");
  687. await setTaskNotificationSwitch(false);
  688. await closeSettings();
  689. expect(await notify({})).toContain(
  690. 'E2E_JARVISHOST_NOTIFY ok {"shown":false,"reason":"disabled"}',
  691. );
  692. await openSettingsSection("general");
  693. await setTaskNotificationSwitch(true);
  694. await closeSettings();
  695. // 详情页开关(默认开)关掉:不弹,最近操作有一行。
  696. await openPluginManagementSettings();
  697. await openInstalledPluginSettingsDetail(PLUGIN_ID);
  698. await browser.waitUntil(async () => (await readNotificationsSwitch(PLUGIN_ID)) === true, {
  699. timeout: 15000,
  700. timeoutMsg: "the notifications switch should default to on",
  701. });
  702. await capturePluginManualReview(CASE_ID, "notifications-switch-zh-CN-zai-light");
  703. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  704. await capturePluginManualReview(CASE_ID, "notifications-switch-en-US-zai-dark");
  705. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  706. await browser.execute(
  707. (switchTestId, id) =>
  708. document
  709. .querySelector<HTMLElement>(`[data-testid="${switchTestId}"][data-plugin-id="${id}"]`)
  710. ?.click(),
  711. TID_EXTENSION_PERMISSIONS_NOTIFICATIONS,
  712. PLUGIN_ID,
  713. );
  714. await browser.waitUntil(async () => (await readNotificationsSwitch(PLUGIN_ID)) === false, {
  715. timeout: 15000,
  716. timeoutMsg: "the notifications switch should turn off",
  717. });
  718. await browser.waitUntil(
  719. async () => (await readPermissionActions(PLUGIN_ID)).includes("grants.notifications.off"),
  720. { timeout: 15000, timeoutMsg: "recent actions should show the switch change" },
  721. );
  722. await closeSettings();
  723. expect(await notify({})).toContain('E2E_JARVISHOST_NOTIFY ok {"shown":false,"reason":"muted"}');
  724. await openPluginManagementSettings();
  725. await openInstalledPluginSettingsDetail(PLUGIN_ID);
  726. await browser.execute(
  727. (switchTestId, id) =>
  728. document
  729. .querySelector<HTMLElement>(`[data-testid="${switchTestId}"][data-plugin-id="${id}"]`)
  730. ?.click(),
  731. TID_EXTENSION_PERMISSIONS_NOTIFICATIONS,
  732. PLUGIN_ID,
  733. );
  734. await browser.waitUntil(async () => (await readNotificationsSwitch(PLUGIN_ID)) === true, {
  735. timeout: 15000,
  736. timeoutMsg: "the notifications switch should turn back on",
  737. });
  738. await closeSettings();
  739. // 都放开:弹出;标题由宿主加插件名前缀,静音。
  740. expect(await notify({ view: "home" })).toContain('E2E_JARVISHOST_NOTIFY ok {"shown":true}');
  741. const recorded = await readRecordedNotifications();
  742. evidence.recordedNotifications = recorded;
  743. expect(recorded).toHaveLength(1);
  744. expect(recorded[0]).toMatchObject({
  745. title: `${PLUGIN}:E2E title`,
  746. body: "E2E body",
  747. silent: true,
  748. });
  749. // 紧接着第二条:限流,不弹。
  750. expect(await notify({})).toContain(
  751. 'E2E_JARVISHOST_NOTIFY ok {"shown":false,"reason":"rate-limited"}',
  752. );
  753. expect(await readRecordedNotifications()).toHaveLength(1);
  754. // 点了通知:打开该插件声明的视图(先切到启动页,证明是点击打开的)。
  755. await openLauncher();
  756. const beforeClick = await readActiveSidePaneTab();
  757. evidence.activeTabBeforeClick = beforeClick;
  758. expect(beforeClick).not.toBe(`extension-view:${HOME_VIEW}`);
  759. await clickRecordedNotification(0);
  760. await browser.waitUntil(
  761. async () => (await readActiveSidePaneTab()) === `extension-view:${HOME_VIEW}`,
  762. { timeout: 15000, timeoutMsg: "clicking the notification should open the plugin view" },
  763. );
  764. evidence.notificationClickLog = await log.waitFor(
  765. (line) => line.includes("[extension-slots] notification click"),
  766. "the renderer should log the notification click",
  767. );
  768. expect(String(evidence.notificationClickLog)).toContain('"opened":true');
  769. evidence.notifyResults = await notifyResults();
  770. evidence.notificationLogs = (await log.lines()).filter(
  771. (line) => line.includes("notifications.show") || line.includes("show-extension-notification"),
  772. );
  773. // 日志不带标题与正文。
  774. expect(JSON.stringify(evidence.notificationLogs)).not.toContain("E2E title");
  775. expect(JSON.stringify(evidence.notificationLogs)).not.toContain("E2E body");
  776. await setMainFocus(null);
  777. });
  778. // 以下宿主行为以前只由示例插件用例 PLM-JARVIS-1、2 断言(Jarvis 是 App 作用域视图、存数据、申请完全访问)。
  779. it("换代后的 App 作用域视图、App 重启后的数据目录、经 grants.request 申请完全访问", async function () {
  780. this.timeout(600000);
  781. requirePluginManualReview();
  782. // (h) 杀掉扩展进程:App 作用域的视图按新代际重建(新实例 id),页面重新就绪。
  783. await clickNavItem(NAV_ITEM);
  784. const before = await waitForViewPane(
  785. HOME_VIEW,
  786. (item) => item.phase === "running" && item.displayed,
  787. "the app-scoped view should be open before the kill",
  788. );
  789. const pid = await readFixturePid();
  790. expect(pid).toBeGreaterThan(0);
  791. process.kill(pid!, "SIGKILL");
  792. const rebuilt = await waitForViewPane(
  793. HOME_VIEW,
  794. (item) => Number(item.gen) > Number(before.gen) && item.phase === "running",
  795. "the app-scoped view should be rebuilt by the new generation",
  796. 90000,
  797. );
  798. evidence.appViewAfterKill = { before, rebuilt };
  799. expect(rebuilt.scope).toBe("app");
  800. expect(rebuilt.instance).not.toBe(before.instance);
  801. await waitForViewPage(
  802. HOME_VIEW,
  803. (page) => page.dataset.ready === "1",
  804. "the rebuilt app-scoped view page should be ready",
  805. );
  806. await capturePluginManualReview(CASE_ID, "app-view-after-kill-zh-CN-zai-light");
  807. // (i) H6:重启 App 后,dataPath 里上一次写的数据还在(激活时读到的 previous 等于重启前的 count)。
  808. const beforeRestart = parseDataLine(
  809. (await log.lines()).filter((line) => line.includes("E2E_JARVISHOST_DATA ")).at(-1) ?? "",
  810. );
  811. evidence.dataBeforeRestart = beforeRestart;
  812. expect(beforeRestart.count).toBeGreaterThanOrEqual(2);
  813. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  814. afterElectronProcessExit: () => log.mark(),
  815. });
  816. await prepareV4ConversationE2E();
  817. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  818. const afterRestartLine = await log.waitFor(
  819. (line) => line.includes("E2E_JARVISHOST_DATA "),
  820. "the fixture should read its data after the App restarts",
  821. 90000,
  822. );
  823. evidence.dataAfterRestart = afterRestartLine;
  824. expect(parseDataLine(afterRestartLine)).toEqual({
  825. previous: beforeRestart.count,
  826. count: beforeRestart.count + 1,
  827. });
  828. // (j) H12 + 完全访问:清单改成申请 sessions.fullAccess 并「重新加载扩展」后回到待授权;视图经
  829. // grants.request 请宿主弹授权对话框,正文单独写完全访问一行;确认后返回的档位含完全访问。
  830. const manifestPath = join(fixtureHome(), PLUGIN, ".zcode-plugin", "plugin.json");
  831. const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as {
  832. extension: { grants: string[] };
  833. };
  834. manifest.extension.grants = ["sessions.fullAccess", "notifications"];
  835. await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
  836. const beforeReload = (await log.lines()).length;
  837. await reloadExtensionsFromCommandCenter();
  838. await browser.waitUntil(
  839. async () =>
  840. (await log.lines())
  841. .slice(beforeReload)
  842. .some((line) => line.includes(`[${PLUGIN_ID}] activated in`)),
  843. { timeout: 90000, interval: 500, timeoutMsg: "the fixture should activate after reloading" },
  844. );
  845. await clickNavItem(NAV_ITEM);
  846. const view = await waitForViewPane(
  847. HOME_VIEW,
  848. (item) => item.phase === "running" && item.displayed && Boolean(item.sandbox),
  849. "the view should be running after reloading",
  850. 60000,
  851. );
  852. await waitForViewPage(HOME_VIEW, (page) => page.dataset.ready === "1", "view page ready");
  853. const grantLines = async () =>
  854. (await log.lines())
  855. .slice(beforeReload)
  856. .filter((line) => line.includes("E2E_JARVISHOST_GRANTS "));
  857. await callViewTool(view.sandbox ?? "", "requestGrants", {}, false);
  858. const fullDialog = await waitForDialog(
  859. TID_EXTENSION_GRANT_DIALOG,
  860. "grants.request should ask for full access",
  861. );
  862. evidence.fullAccessGrantDialog = fullDialog;
  863. expect(fullDialog).toContain(`允许「${PLUGIN}」读取和操作会话?`);
  864. expect(fullDialog).toContain("完全访问:插件可以把它项目里的会话切到完全访问");
  865. expect(fullDialog).toContain("系统通知");
  866. await capturePluginManualReview(CASE_ID, "grants-request-full-access-zh-CN-zai-light");
  867. await closeDialog(TID_EXTENSION_GRANT_DIALOG, true);
  868. await browser.waitUntil(async () => (await grantLines()).length === 1, {
  869. timeout: 15000,
  870. timeoutMsg: "grants.request should return after granting full access",
  871. });
  872. evidence.fullAccessGrantResult = (await grantLines())[0];
  873. expect((await grantLines())[0]).toContain(
  874. "E2E_JARVISHOST_GRANTS ok granted=sessions.fullAccess,notifications",
  875. );
  876. });
  877. });