browser-session-recent-visits.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. import { createServer, type Server, type ServerResponse } from "node:http";
  2. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  3. import {
  4. TID_BROWSER_ADDRESS_INPUT,
  5. TID_BROWSER_LOAD_ERROR,
  6. TID_BROWSER_WEBVIEW,
  7. TID_SETTINGS_BACK_BUTTON,
  8. TID_SETTINGS_PAGE,
  9. TID_SETTINGS_SECTION_NAV,
  10. TID_SIDE_PANE_TOGGLE,
  11. TID_TASK_SETTINGS_BUTTON,
  12. testId,
  13. } from "@zcode/shared/test-ids";
  14. import { readBrowserTabIds } from "#e2e/helpers/browser-side-pane";
  15. import {
  16. DEFAULT_WORKSPACE,
  17. clearAppData,
  18. clickTestIdByDom,
  19. waitForWorkspaceApp,
  20. } from "#e2e/helpers/desktop-app";
  21. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  22. import { sel } from "#e2e/helpers/selectors";
  23. const RECENT_LIST = '[data-testid="browser-recent-visits"]';
  24. const RECENT_BUTTON = `${RECENT_LIST} button[data-browser-recent-url]`;
  25. const ACTIVE_PANEL = '[role="tabpanel"][data-state="active"]';
  26. const ADDRESS = `${ACTIVE_PANEL} [data-testid="${TID_BROWSER_ADDRESS_INPUT}"]`;
  27. type ScopeWindow = Window & {
  28. __zcodeSessionStoreE2E?: {
  29. getState(): {
  30. setActiveTaskId(workspacePath: string, taskId: string): void;
  31. removeTaskState(workspacePath: string, taskId: string, workspaceIdentity?: string): void;
  32. workspaces: Record<string, { activeTaskId: string | null }>;
  33. };
  34. };
  35. };
  36. type GuestSnapshot = {
  37. id: number;
  38. url: string;
  39. title: string;
  40. ready: boolean;
  41. iframeLoaded: boolean;
  42. };
  43. let server: Server | undefined;
  44. let origin = "";
  45. let titleReleased = false;
  46. let redirectRecovery = false;
  47. const titleResponses = new Set<ServerResponse>();
  48. // Spec:docs/browser-use/2026-10-28-browser-session-recent-visits.md,BRV-03/04/05/06 的 human 候选。
  49. // 与既有 side-pane-scope 候选一样,只用 bridge 准备 owner;不写最近访问 store 或伪造导航事件。
  50. // 不覆盖真实 CLI 会话创建、跨会话/远端隔离、后台归属、Agent 空白 guest 和 20 条上限。
  51. describe("Browser session recent visits (manual-review/pending)", () => {
  52. before(async () => {
  53. server = createFixtureServer();
  54. origin = await listen(server);
  55. });
  56. after(async () => {
  57. for (const response of titleResponses) response.destroy();
  58. titleResponses.clear();
  59. if (server?.listening) {
  60. await new Promise<void>((resolve, reject) => {
  61. server!.close((error) => (error ? reject(error) : resolve()));
  62. server!.closeAllConnections();
  63. });
  64. }
  65. await browser.electron.restoreAllMocks();
  66. await clearAppData();
  67. });
  68. it("BRV-03/04/05: keeps visits on blank tabs, updates metadata without reordering, and opens a saved URL", async function () {
  69. this.timeout(180_000);
  70. await prepareV4ConversationE2E({ skipProvider: true });
  71. const ownerA = `E2E_BROWSER_RECENT_A_${Date.now()}`;
  72. const ownerB = `${ownerA}_B`;
  73. await setActiveOwner(ownerA);
  74. await openFirstBrowserTab();
  75. const sourceA = await activeBrowserTabId();
  76. await waitForBrowserEmpty();
  77. expect(await recentUrls()).toEqual([]);
  78. expect(await activeGuestId()).toBeNull();
  79. const pageA = `${origin}/page-a`;
  80. const pageB = `${origin}/page-b`;
  81. await navigate(pageA);
  82. await waitForGuest(pageA, "Page A");
  83. const sourceB = await openBlankBrowserTab();
  84. await navigate(pageB);
  85. await waitForGuest(pageB, "Page B");
  86. const observer = await openBlankBrowserTab();
  87. await waitForRecentUrls([pageB, pageA]);
  88. await expectRecentVisitsCentered();
  89. expect(await recentText(pageA)).toContain("Page A");
  90. expect(await recentText(pageB)).toContain("Page B");
  91. expect(await recentText(pageA)).toContain(pageA);
  92. expect(await recentText(pageB)).toContain(pageB);
  93. expect(await activeGuestId()).toBeNull();
  94. // A 已是旧记录,再释放它的标题;若元数据被当成访问,列表会错误地变成 A/B。
  95. await browser.waitUntil(async () => titleResponses.size > 0, {
  96. timeout: 15_000,
  97. timeoutMsg: "页面没有请求受控的迟到标题",
  98. });
  99. titleReleased = true;
  100. for (const response of titleResponses) response.end("Updated title A");
  101. titleResponses.clear();
  102. await browser.waitUntil(async () => (await recentText(pageA)).includes("Updated title A"), {
  103. timeout: 15_000,
  104. timeoutMsg: "旧页面标题没有更新最近访问条目",
  105. });
  106. expect(await recentUrls()).toEqual([pageB, pageA]);
  107. // 切换由 bridge 提供的 owner,只验证 UI 隔离,不代表真实 CLI 会话生命周期。
  108. await setActiveOwner(ownerB);
  109. await browser.waitUntil(async () => (await readBrowserTabIds()).length === 0, {
  110. timeout: 15_000,
  111. timeoutMsg: "切换 owner 后仍显示旧 Browser tab",
  112. });
  113. await openFirstBrowserTab();
  114. await waitForBrowserEmpty();
  115. expect(await recentUrls()).toEqual([]);
  116. expect(await activeGuestId()).toBeNull();
  117. await setActiveOwner(ownerA);
  118. await activateTab(observer);
  119. await waitForRecentUrls([pageB, pageA]);
  120. await activateTab(sourceB);
  121. await navigate(pageA);
  122. await waitForGuest(pageA, "Updated title A");
  123. await activateTab(observer);
  124. await waitForRecentUrls([pageA, pageB]);
  125. await closeTab(sourceA);
  126. await closeTab(sourceB);
  127. await activateTab(observer);
  128. await waitForRecentUrls([pageA, pageB]);
  129. await $(ADDRESS).setValue("https://draft.example/path");
  130. await expect($(ADDRESS)).toHaveValue("https://draft.example/path");
  131. await $(`${ACTIVE_PANEL} ${RECENT_LIST}`).waitForDisplayed();
  132. expect(await recentUrls()).toEqual([pageA, pageB]);
  133. expect(await activeGuestId()).toBeNull();
  134. // 原页面均已关闭;只认当前空 tab 的新 guest,不能拿其他 tab 的旧 URL 当导航成功。
  135. await clickRecentUrl(pageB);
  136. const reopened = await waitForGuest(pageB, "Page B");
  137. expect(await activeBrowserTabId()).toBe(observer);
  138. expect(await readBrowserTabIds()).toEqual([observer]);
  139. expect(await activeGuestId()).toBe(reopened.id);
  140. const checkTab = await openBlankBrowserTab();
  141. await waitForRecentUrls([pageB, pageA]);
  142. await focusRecentUrlByKeyboard(pageA);
  143. await browser.keys("Enter");
  144. await waitForGuest(pageA, "Updated title A");
  145. expect(await activeBrowserTabId()).toBe(checkTab);
  146. const iframeTab = await openBlankBrowserTab();
  147. await waitForRecentUrls([pageA, pageB]);
  148. const parentUrl = `${origin}/iframe-parent`;
  149. await activateTab(observer);
  150. await navigate(parentUrl);
  151. await waitForGuest(parentUrl, "Iframe parent", true);
  152. await activateTab(iframeTab);
  153. await waitForRecentUrls([parentUrl, pageA, pageB]);
  154. await activateTab(observer);
  155. await navigate(`${origin}/failure`);
  156. await $(`${ACTIVE_PANEL} [data-testid="${TID_BROWSER_LOAD_ERROR}"]`).waitForDisplayed({
  157. timeout: 30_000,
  158. });
  159. await activateTab(iframeTab);
  160. await waitForRecentUrls([parentUrl, pageA, pageB]);
  161. });
  162. it("BRV-09: recent visits survive app restart without restoring Browser tabs", async function () {
  163. this.timeout(180_000);
  164. await prepareV4ConversationE2E({ skipProvider: true });
  165. const owner = `E2E_BROWSER_RECENT_RESTART_${Date.now()}`;
  166. await setActiveOwner(owner);
  167. await openFirstBrowserTab();
  168. const page = `${origin}/page-b`;
  169. await navigate(page);
  170. await waitForGuest(page, "Page B");
  171. await openBlankBrowserTab();
  172. await waitForRecentUrls([page]);
  173. await reloadElectronSessionPreservingBrowserProfile(browser);
  174. await prepareV4ConversationE2E({ skipProvider: true });
  175. await setActiveOwner(owner);
  176. await openFirstBrowserTab();
  177. await waitForRecentUrls([page]);
  178. expect(await readBrowserTabIds()).toHaveLength(1);
  179. expect(await activeGuestId()).toBeNull();
  180. });
  181. it("BRV-14: removes only the selected scope visit without navigation and persists deletion", async function () {
  182. this.timeout(180_000);
  183. await prepareV4ConversationE2E({ skipProvider: true });
  184. const ownerA = `E2E_BROWSER_RECENT_DELETE_${Date.now()}`;
  185. const ownerB = `${ownerA}_B`;
  186. const pageA = `${origin}/page-b?delete=a`;
  187. const pageB = `${origin}/page-b?delete=b`;
  188. await setActiveOwner(ownerB);
  189. await openFirstBrowserTab();
  190. await navigate(pageA);
  191. await waitForGuest(pageA, "Page B");
  192. const otherObserver = await openBlankBrowserTab();
  193. await waitForRecentUrls([pageA]);
  194. await setActiveOwner(ownerA);
  195. await openFirstBrowserTab();
  196. await navigate(pageA);
  197. await waitForGuest(pageA, "Page B");
  198. await navigate(pageB);
  199. await waitForGuest(pageB, "Page B");
  200. const observer = await openBlankBrowserTab();
  201. await waitForRecentUrls([pageB, pageA]);
  202. const tabsBefore = await readBrowserTabIds();
  203. const removeA = await $(`${ACTIVE_PANEL} button[data-browser-recent-remove-url="${pageA}"]`);
  204. await expect(removeA).toHaveAttribute(
  205. "aria-label",
  206. /Remove from recent visits|从最近访问中删除/u,
  207. );
  208. await removeA.click();
  209. await waitForRecentUrls([pageB]);
  210. expect(await activeGuestId()).toBeNull();
  211. expect(await activeBrowserTabId()).toBe(observer);
  212. expect(await readBrowserTabIds()).toEqual(tabsBefore);
  213. await setActiveOwner(ownerB);
  214. await activateTab(otherObserver);
  215. await waitForRecentUrls([pageA]);
  216. await reloadElectronSessionPreservingBrowserProfile(browser);
  217. await prepareV4ConversationE2E({ skipProvider: true });
  218. await setActiveOwner(ownerA);
  219. await openFirstBrowserTab();
  220. await waitForRecentUrls([pageB]);
  221. expect(await activeGuestId()).toBeNull();
  222. await browser.execute((selector) => {
  223. document.querySelector<HTMLButtonElement>(selector)?.focus();
  224. }, `${ACTIVE_PANEL} button[data-browser-recent-remove-url]`);
  225. await browser.keys("Enter");
  226. await waitForBrowserEmpty();
  227. expect(await recentUrls()).toEqual([]);
  228. expect(await activeGuestId()).toBeNull();
  229. const remainingKeys = await browser.execute((owner) => {
  230. return Object.keys(localStorage).filter((key) => {
  231. if (!key.startsWith("zcode-browser-recent-visits:")) return false;
  232. return (
  233. (JSON.parse(key.slice("zcode-browser-recent-visits:".length)) as string[])[2] === owner
  234. );
  235. });
  236. }, ownerA);
  237. expect(remainingKeys).toEqual([]);
  238. });
  239. it("BRV-10: browser cache clear preserves visits and clear-all removes them", async function () {
  240. this.timeout(180_000);
  241. await prepareV4ConversationE2E({ skipProvider: true });
  242. await setActiveOwner(`E2E_BROWSER_RECENT_CLEAR_${Date.now()}`);
  243. await openFirstBrowserTab();
  244. const page = `${origin}/page-b`;
  245. await navigate(page);
  246. await waitForGuest(page, "Page B");
  247. const observer = await openBlankBrowserTab();
  248. await waitForRecentUrls([page]);
  249. await openBrowserSettings();
  250. await clickSettingsButton(/clear cache|清除缓存/iu);
  251. await $(sel(TID_SETTINGS_BACK_BUTTON)).click();
  252. await activateTab(observer);
  253. await waitForRecentUrls([page]);
  254. await openBrowserSettings();
  255. await clickSettingsButton(/clear all|清除全部/iu);
  256. await clickSettingsButton(/clear data|确认清除/iu, '[role="alertdialog"]');
  257. await $(sel(TID_SETTINGS_BACK_BUTTON)).click();
  258. await activateTab(observer);
  259. await waitForBrowserEmpty();
  260. expect(await recentUrls()).toEqual([]);
  261. });
  262. it("BRV-12: recent visits cap scopes and bound persisted favicons", async function () {
  263. await prepareV4ConversationE2E({ skipProvider: true });
  264. const capSeed = await browser.execute(() => {
  265. const now = Date.now();
  266. for (let index = 0; index <= 50; index += 1) {
  267. const sessionId = `E2E_SCOPE_CAP_${index}`;
  268. const scopeKey = JSON.stringify(["/workspace", "", sessionId]);
  269. localStorage.setItem(
  270. `zcode-browser-recent-visits:${scopeKey}`,
  271. JSON.stringify([
  272. {
  273. url: `https://example.test/${index}`,
  274. title: "Page",
  275. faviconUrl: "data:image/png;base64," + "A".repeat(1024),
  276. lastVisitedAt: now + index,
  277. },
  278. ]),
  279. );
  280. }
  281. const scopeKey = JSON.stringify(["/workspace", "", "E2E_SCOPE_TRIGGER"]);
  282. localStorage.setItem(
  283. `zcode-browser-recent-visits:${scopeKey}`,
  284. JSON.stringify([
  285. {
  286. url: "https://example.test/trigger",
  287. title: "Trigger",
  288. faviconUrl: null,
  289. lastVisitedAt: now + 100,
  290. },
  291. ]),
  292. );
  293. return { triggerKey: `zcode-browser-recent-visits:${scopeKey}` };
  294. });
  295. await reloadElectronSessionPreservingBrowserProfile(browser);
  296. await prepareV4ConversationE2E({ skipProvider: true });
  297. const result = await browser.execute((triggerKey) => {
  298. const visits = JSON.parse(localStorage.getItem(triggerKey) ?? "[]");
  299. const keys = Array.from({ length: localStorage.length }, (_, index) =>
  300. localStorage.key(index),
  301. ).filter((key): key is string => key?.startsWith("zcode-browser-recent-visits:") === true);
  302. const values = keys.map((key) => JSON.parse(localStorage.getItem(key) ?? "[]"));
  303. return {
  304. scopeCount: keys.length,
  305. triggerLoaded: visits.length === 1,
  306. allFaviconsBounded: values
  307. .flat()
  308. .every((visit) => visit.faviconUrl === null || visit.faviconUrl.length <= 2 * 1024),
  309. };
  310. }, capSeed.triggerKey);
  311. expect(result.scopeCount).toBeLessThanOrEqual(50);
  312. expect(result.triggerLoaded).toBe(true);
  313. expect(result.allFaviconsBounded).toBe(true);
  314. expect(
  315. await browser.execute(() =>
  316. localStorage.getItem(
  317. `zcode-browser-recent-visits:${JSON.stringify(["/workspace", "", "E2E_SCOPE_CAP_0"])}`,
  318. ),
  319. ),
  320. ).toBeNull();
  321. });
  322. it("BRV-13: a data favicon stays visible but is not persisted", async function () {
  323. this.timeout(180_000);
  324. await prepareV4ConversationE2E({ skipProvider: true });
  325. const owner = `E2E_BROWSER_RECENT_FAVICON_${Date.now()}`;
  326. await setActiveOwner(owner);
  327. await openFirstBrowserTab();
  328. const page = `${origin}/favicon`;
  329. await navigate(page);
  330. await waitForGuest(page, "Favicon Page");
  331. const source = await activeBrowserTabId();
  332. const observer = await openBlankBrowserTab();
  333. await waitForRecentUrls([page]);
  334. await browser.waitUntil(async () => (await recentText(page)).includes("Favicon Page"), {
  335. timeout: 15_000,
  336. timeoutMsg: "页面标题没有进入最近访问记录",
  337. });
  338. expect(await recentFaviconUrl(page)).toContain("data:image/svg+xml,");
  339. const persistedKey = `zcode-browser-recent-visits:${JSON.stringify([DEFAULT_WORKSPACE, "", owner])}`;
  340. const storedDataFavicon =
  341. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC";
  342. await browser.execute((key) => {
  343. const storage = window.localStorage;
  344. const originalSetItem = storage.setItem.bind(storage);
  345. (window as Window & { __recentVisitWrites?: number }).__recentVisitWrites = 0;
  346. storage.setItem = (name, value) => {
  347. if (name.startsWith("zcode-browser-recent-visits:")) {
  348. (window as Window & { __recentVisitWrites?: number }).__recentVisitWrites! += 1;
  349. }
  350. originalSetItem(name, value);
  351. };
  352. if (!storage.getItem(key)) throw new Error("最近访问记录缺少初始持久化数据");
  353. }, persistedKey);
  354. await activateTab(source);
  355. const guestId = await browser.electron.execute((electron, targetUrl) => {
  356. const guest = electron.webContents
  357. .getAllWebContents()
  358. .find((contents) => contents.getURL() === targetUrl);
  359. return guest?.id ?? null;
  360. }, page);
  361. if (guestId === null) throw new Error("Favicon fixture guest is missing");
  362. await browser.electron.execute(
  363. async (electron, id, favicon) => {
  364. const guest = electron.webContents.fromId(id);
  365. if (!guest) throw new Error("Favicon fixture guest is missing");
  366. await guest.executeJavaScript(`(() => {
  367. const link = document.createElement("link");
  368. link.rel = "icon";
  369. link.href = ${JSON.stringify(favicon)};
  370. document.head.append(link);
  371. })()`);
  372. },
  373. guestId,
  374. storedDataFavicon,
  375. );
  376. await activateTab(observer);
  377. await browser.waitUntil(async () => (await recentFaviconUrl(page)) === storedDataFavicon, {
  378. timeout: 15_000,
  379. timeoutMsg: "真实页面 favicon 事件没有更新内存中的最近访问图标",
  380. });
  381. const storageResult = await browser.execute(
  382. (key) => ({
  383. record: JSON.parse(window.localStorage.getItem(key) ?? "null"),
  384. writes: (window as Window & { __recentVisitWrites?: number }).__recentVisitWrites ?? -1,
  385. }),
  386. persistedKey,
  387. );
  388. expect(storageResult.record[0].faviconUrl).toBeNull();
  389. expect(storageResult.writes).toBe(0);
  390. await browser.electron.execute(
  391. async (electron, id, favicon) => {
  392. const guest = electron.webContents.fromId(id);
  393. if (!guest) throw new Error("Favicon fixture guest is missing");
  394. await guest.executeJavaScript(
  395. `document.querySelector('link[rel="icon"]').href = ${JSON.stringify(favicon)}`,
  396. );
  397. },
  398. guestId,
  399. storedDataFavicon,
  400. );
  401. await activateTab(observer);
  402. await browser.waitUntil(async () => (await recentFaviconUrl(page)) === storedDataFavicon, {
  403. timeout: 15_000,
  404. timeoutMsg: "相同 favicon 再次到达后不应改变内存展示值",
  405. });
  406. const repeatResult = await browser.execute(
  407. (key) => ({
  408. record: JSON.parse(window.localStorage.getItem(key) ?? "null"),
  409. writes: (window as Window & { __recentVisitWrites?: number }).__recentVisitWrites ?? -1,
  410. }),
  411. persistedKey,
  412. );
  413. expect(repeatResult.writes).toBe(0);
  414. expect(repeatResult.record[0].faviconUrl).toBeNull();
  415. await reloadElectronSessionPreservingBrowserProfile(browser);
  416. await prepareV4ConversationE2E({ skipProvider: true });
  417. await setActiveOwner(owner);
  418. await openFirstBrowserTab();
  419. const restartedObserver = await openBlankBrowserTab();
  420. await waitForRecentUrls([page]);
  421. await activateTab(restartedObserver);
  422. expect(await recentFaviconUrl(page)).toBe("");
  423. });
  424. it("BRV-06: automatic recovery does not reorder recent visits", async function () {
  425. this.timeout(120_000);
  426. await prepareV4ConversationE2E({ skipProvider: true });
  427. await setActiveOwner(`E2E_BROWSER_RECOVERY_${Date.now()}`);
  428. await openFirstBrowserTab();
  429. const source = await activeBrowserTabId();
  430. const recoveryPage = `${origin}/recovery`;
  431. const otherPage = `${origin}/page-b`;
  432. await navigate(recoveryPage);
  433. await waitForGuest(recoveryPage, "Recovery Page");
  434. const other = await openBlankBrowserTab();
  435. await navigate(otherPage);
  436. await waitForGuest(otherPage, "Page B");
  437. const observer = await openBlankBrowserTab();
  438. await waitForRecentUrls([otherPage, recoveryPage]);
  439. await activateTab(source);
  440. await crashActiveGuest();
  441. await waitForGuest(recoveryPage, "Recovery Page");
  442. await activateTab(observer);
  443. await waitForRecentUrls([otherPage, recoveryPage]);
  444. await closeTab(source);
  445. await closeTab(other);
  446. await closeTab(observer);
  447. });
  448. it("BRV-06: redirected recovery cannot suppress a later in-page visit", async function () {
  449. this.timeout(120_000);
  450. await prepareV4ConversationE2E({ skipProvider: true });
  451. await setActiveOwner(`E2E_BROWSER_REDIRECT_RECOVERY_${Date.now()}`);
  452. await openFirstBrowserTab();
  453. const source = await activeBrowserTabId();
  454. const recoveryPage = `${origin}/recovery`;
  455. const redirectPage = `${origin}/recovery-redirect`;
  456. const otherPage = `${origin}/page-b`;
  457. await navigate(recoveryPage);
  458. await waitForGuest(recoveryPage, "Recovery Page");
  459. const other = await openBlankBrowserTab();
  460. await navigate(otherPage);
  461. await waitForGuest(otherPage, "Page B");
  462. const observer = await openBlankBrowserTab();
  463. await waitForRecentUrls([otherPage, recoveryPage]);
  464. await activateTab(source);
  465. redirectRecovery = true;
  466. try {
  467. await crashActiveGuest();
  468. await waitForGuest(redirectPage, "Recovery Redirect");
  469. } finally {
  470. redirectRecovery = false;
  471. }
  472. await activateTab(observer);
  473. await waitForRecentUrls([redirectPage, otherPage, recoveryPage]);
  474. await activateTab(source);
  475. const guestId = await activeGuestId();
  476. if (guestId === null) throw new Error("恢复后的 guest 不存在");
  477. await browser.electron.execute(async (electron, id) => {
  478. await electron.webContents
  479. .fromId(id)!
  480. .executeJavaScript('document.querySelector("a[data-e2e-revisit]").click()');
  481. }, guestId);
  482. await waitForGuest(recoveryPage, "Recovery Page");
  483. await activateTab(observer);
  484. await waitForRecentUrls([recoveryPage, redirectPage, otherPage]);
  485. await closeTab(source);
  486. await closeTab(other);
  487. await closeTab(observer);
  488. });
  489. });
  490. async function crashActiveGuest(): Promise<void> {
  491. const oldId = await activeGuestId();
  492. if (oldId === null) throw new Error("缺少待崩溃的 guest");
  493. await browser.electron.execute((electron, id) => {
  494. electron.webContents.fromId(id)!.forcefullyCrashRenderer();
  495. }, oldId);
  496. await browser.waitUntil(
  497. async () => {
  498. try {
  499. const id = await activeGuestId();
  500. return id !== null && id !== oldId;
  501. } catch {
  502. return false;
  503. }
  504. },
  505. { timeout: 30_000, timeoutMsg: "崩溃后未创建替代 guest" },
  506. );
  507. }
  508. async function openBrowserSettings(): Promise<void> {
  509. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 15_000 });
  510. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15_000 });
  511. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "browser"), { timeout: 15_000 });
  512. await $("[data-settings-content-frame]").waitForDisplayed({ timeout: 15_000 });
  513. }
  514. async function clickSettingsButton(
  515. label: RegExp,
  516. root = "[data-settings-content-frame]",
  517. ): Promise<void> {
  518. for (const candidate of await $$(`${root} button`)) {
  519. if (label.test(await candidate.getText())) {
  520. await candidate.click();
  521. return;
  522. }
  523. }
  524. throw new Error(`设置页中没有匹配的操作按钮:${label}`);
  525. }
  526. async function openFirstBrowserTab(): Promise<void> {
  527. // 通用 helper 的 Meta+Alt+B 只适用于 macOS;直接使用真实按钮保持跨平台一致。
  528. const entry = '[data-side-pane-open-tab-item="browser"]';
  529. if (!(await $(entry).isDisplayed())) {
  530. const toggle = await $(`[data-testid="${TID_SIDE_PANE_TOGGLE}"]`);
  531. await toggle.waitForDisplayed({ timeout: 15_000 });
  532. await toggle.click();
  533. }
  534. await $(entry).waitForDisplayed({ timeout: 15_000 });
  535. await $(entry).click();
  536. await $(ADDRESS).waitForDisplayed({ timeout: 15_000 });
  537. }
  538. async function setActiveOwner(ownerId: string): Promise<void> {
  539. await browser.execute(
  540. (workspacePath, taskId) => {
  541. const store = (window as ScopeWindow).__zcodeSessionStoreE2E;
  542. if (!store) throw new Error("缺少 E2E session store bridge");
  543. store.getState().setActiveTaskId(workspacePath, taskId);
  544. },
  545. DEFAULT_WORKSPACE,
  546. ownerId,
  547. );
  548. await browser.waitUntil(
  549. () =>
  550. browser.execute(
  551. (workspacePath, taskId) =>
  552. (window as ScopeWindow).__zcodeSessionStoreE2E?.getState().workspaces[workspacePath]
  553. ?.activeTaskId === taskId,
  554. DEFAULT_WORKSPACE,
  555. ownerId,
  556. ),
  557. { timeout: 15_000, timeoutMsg: `Browser fixture owner ${ownerId} 没有就绪` },
  558. );
  559. }
  560. async function waitForBrowserEmpty(): Promise<void> {
  561. await browser.waitUntil(
  562. () =>
  563. browser.execute((panelSelector) => {
  564. const text = document.querySelector<HTMLElement>(panelSelector)?.innerText ?? "";
  565. return (
  566. text.includes("Paste or type a URL to open a page.") ||
  567. text.includes("粘贴或输入 URL 以打开网页。")
  568. );
  569. }, ACTIVE_PANEL),
  570. { timeout: 15_000, timeoutMsg: "没有显示既有 browser.empty 文案" },
  571. );
  572. }
  573. async function activeBrowserTabId(): Promise<string> {
  574. const tab = await $('[data-side-pane-tab-id^="browser:"][data-state="active"]');
  575. await tab.waitForDisplayed({ timeout: 15_000 });
  576. const id = await tab.getAttribute("data-side-pane-tab-id");
  577. if (!id) throw new Error("没有 active Browser tab");
  578. return id;
  579. }
  580. async function activateTab(id: string): Promise<void> {
  581. const tab = await $(`[data-side-pane-tab-id="${id}"]`);
  582. await tab.click();
  583. await expect(tab).toHaveAttribute("data-state", "active");
  584. await $(ADDRESS).waitForDisplayed({ timeout: 15_000 });
  585. }
  586. async function openBlankBrowserTab(): Promise<string> {
  587. const before = await readBrowserTabIds();
  588. await $("[data-side-pane-add-trigger]").click();
  589. const launcher = await $(`${ACTIVE_PANEL} [data-side-pane-open-tab-item="browser"]`);
  590. await launcher.waitForDisplayed({ timeout: 15_000 });
  591. await launcher.click();
  592. await browser.waitUntil(async () => (await readBrowserTabIds()).length === before.length + 1, {
  593. timeout: 15_000,
  594. timeoutMsg: "新建 Browser tab 未完成",
  595. });
  596. const id = await activeBrowserTabId();
  597. expect(before).not.toContain(id);
  598. await $(ADDRESS).waitForDisplayed({ timeout: 15_000 });
  599. expect(await activeGuestId()).toBeNull();
  600. return id;
  601. }
  602. async function closeTab(id: string): Promise<void> {
  603. const tab = await $(`[data-side-pane-tab-id="${id}"]`);
  604. await tab.moveTo();
  605. await tab.$("button").click();
  606. await tab.waitForExist({ reverse: true, timeout: 15_000 });
  607. }
  608. async function navigate(url: string): Promise<void> {
  609. const address = await $(ADDRESS);
  610. await address.waitForDisplayed({ timeout: 15_000 });
  611. await address.setValue(url);
  612. await address.click();
  613. await browser.keys("Enter");
  614. }
  615. async function activeGuestId(): Promise<number | null> {
  616. return browser.execute((selector) => {
  617. const webview = document.querySelector<HTMLElement & { getWebContentsId(): number }>(selector);
  618. return webview ? webview.getWebContentsId() : null;
  619. }, `${ACTIVE_PANEL} [data-testid="${TID_BROWSER_WEBVIEW}"]`);
  620. }
  621. async function waitForGuest(
  622. url: string,
  623. title: string,
  624. iframeLoaded = false,
  625. ): Promise<GuestSnapshot> {
  626. let latest: GuestSnapshot | null = null;
  627. await browser.waitUntil(
  628. async () => {
  629. const id = await activeGuestId();
  630. if (id === null) return false;
  631. latest = (await browser.electron.execute(async (electron, guestId) => {
  632. const guest = electron.webContents.fromId(guestId);
  633. if (!guest || guest.isDestroyed() || guest.isLoading()) return null;
  634. const content = await guest.executeJavaScript(`({
  635. ready: document.readyState === "complete",
  636. iframeLoaded: document.querySelector("iframe")?.contentDocument?.querySelector("[data-e2e-child]") !== null &&
  637. Boolean(document.querySelector("iframe")?.contentDocument?.querySelector("[data-e2e-child]"))
  638. })`);
  639. return { id: guest.id, url: guest.getURL(), title: guest.getTitle(), ...content };
  640. }, id)) as unknown as GuestSnapshot | null;
  641. return (
  642. latest?.url === url &&
  643. latest.title === title &&
  644. latest.ready &&
  645. (!iframeLoaded || latest.iframeLoaded)
  646. );
  647. },
  648. { timeout: 30_000, timeoutMsg: `当前 guest 未完成导航 ${url} / ${title}` },
  649. );
  650. if (!latest) throw new Error(`缺少 guest ${url}`);
  651. return latest;
  652. }
  653. async function expectRecentVisitsCentered(): Promise<void> {
  654. const geometry = await browser.execute(() => {
  655. const viewport = document.querySelector<HTMLElement>('[data-testid="browser-recent-visits"]');
  656. const content = document.querySelector<HTMLElement>(
  657. '[data-testid="browser-recent-visits-content"]',
  658. );
  659. if (!viewport || !content) return null;
  660. const viewportRect = viewport.getBoundingClientRect();
  661. const contentRect = content.getBoundingClientRect();
  662. return {
  663. contentCenterY: contentRect.top + contentRect.height / 2,
  664. contentCenterX: contentRect.left + contentRect.width / 2,
  665. contentCenterRatioY:
  666. (contentRect.top + contentRect.height / 2 - viewportRect.top) / viewportRect.height,
  667. viewportCenterY: viewportRect.top + viewportRect.height / 2,
  668. viewportCenterX: viewportRect.left + viewportRect.width / 2,
  669. viewportWidth: viewportRect.width,
  670. contentWidth: contentRect.width,
  671. };
  672. });
  673. expect(geometry).not.toBeNull();
  674. expect(geometry!.contentCenterRatioY).toBeCloseTo(0.4, 2);
  675. expect(Math.abs(geometry!.contentCenterX - geometry!.viewportCenterX)).toBeLessThanOrEqual(2);
  676. expect(geometry!.contentWidth).toBeLessThanOrEqual(672);
  677. expect(geometry!.contentWidth).toBeLessThanOrEqual(geometry!.viewportWidth);
  678. }
  679. async function recentUrls(): Promise<string[]> {
  680. return browser.execute(
  681. (selector) =>
  682. Array.from(
  683. document.querySelectorAll<HTMLButtonElement>(selector),
  684. (button) => button.getAttribute("data-browser-recent-url") ?? "",
  685. ),
  686. `${ACTIVE_PANEL} ${RECENT_BUTTON}`,
  687. );
  688. }
  689. async function waitForRecentUrls(expected: string[]): Promise<void> {
  690. await $(`${ACTIVE_PANEL} ${RECENT_LIST}`).waitForDisplayed({ timeout: 15_000 });
  691. await browser.waitUntil(
  692. async () => JSON.stringify(await recentUrls()) === JSON.stringify(expected),
  693. {
  694. timeout: 15_000,
  695. timeoutMsg: `最近访问列表未收敛到 ${expected.join(", ")}`,
  696. },
  697. );
  698. }
  699. async function recentFaviconUrl(url: string): Promise<string> {
  700. return browser.execute(
  701. (selector, target) => {
  702. const item = Array.from(document.querySelectorAll<HTMLButtonElement>(selector)).find(
  703. (button) => button.getAttribute("data-browser-recent-url") === target,
  704. );
  705. return item?.querySelector("img")?.getAttribute("src") ?? "";
  706. },
  707. `${ACTIVE_PANEL} ${RECENT_BUTTON}`,
  708. url,
  709. );
  710. }
  711. async function recentText(url: string): Promise<string> {
  712. return browser.execute(
  713. (selector, target) =>
  714. Array.from(document.querySelectorAll<HTMLButtonElement>(selector)).find(
  715. (button) => button.getAttribute("data-browser-recent-url") === target,
  716. )?.innerText ?? "",
  717. `${ACTIVE_PANEL} ${RECENT_BUTTON}`,
  718. url,
  719. );
  720. }
  721. async function clickRecentUrl(url: string): Promise<void> {
  722. for (const button of await $$(`${ACTIVE_PANEL} ${RECENT_BUTTON}`)) {
  723. if ((await button.getAttribute("data-browser-recent-url")) === url) {
  724. await button.click();
  725. return;
  726. }
  727. }
  728. throw new Error(`最近访问列表中没有 URL ${url}`);
  729. }
  730. async function focusRecentUrlByKeyboard(url: string): Promise<void> {
  731. await $(ADDRESS).click();
  732. for (let step = 0; step < 20; step += 1) {
  733. await browser.keys("Tab");
  734. const focusedUrl = await browser.execute(() =>
  735. (document.activeElement as HTMLElement | null)?.getAttribute("data-browser-recent-url"),
  736. );
  737. if (focusedUrl === url) return;
  738. }
  739. throw new Error(`Tab 焦点没有到达最近访问 URL ${url}`);
  740. }
  741. function createFixtureServer(): Server {
  742. return createServer((request, response) => {
  743. response.setHeader("cache-control", "no-store");
  744. if (request.url === "/failure") {
  745. request.socket.destroy();
  746. return;
  747. }
  748. if (request.url === "/late-title") {
  749. if (titleReleased) response.end("Updated title A");
  750. else {
  751. titleResponses.add(response);
  752. response.once("close", () => titleResponses.delete(response));
  753. }
  754. return;
  755. }
  756. if (request.url === "/recovery" && redirectRecovery) {
  757. response.writeHead(302, { location: "/recovery-redirect" });
  758. response.end();
  759. return;
  760. }
  761. response.setHeader("content-type", "text/html; charset=utf-8");
  762. if (request.url === "/page-a") {
  763. response.end(
  764. '<!doctype html><title>Page A</title><main>Page A</main><script>fetch("/late-title").then(r => r.text()).then(title => { document.title = title; });</script>',
  765. );
  766. } else if (request.url === "/favicon") {
  767. response.end(
  768. '<!doctype html><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2216%22 height=%2216%22%3E%3Ccircle cx=%228%22 cy=%228%22 r=%228%22 fill=%22red%22/%3E%3C/svg%3E"><title>Favicon Page</title><main>Favicon Page</main>',
  769. );
  770. } else if (request.url === "/recovery") {
  771. response.end("<!doctype html><title>Recovery Page</title><main>Recovery Page</main>");
  772. } else if (request.url === "/recovery-redirect") {
  773. response.end(
  774. '<!doctype html><title>Recovery Redirect</title><a data-e2e-revisit href="/recovery">Revisit recovery</a>',
  775. );
  776. } else if (request.url === "/page-b" || request.url?.startsWith("/page-b?delete=")) {
  777. response.end("<!doctype html><title>Page B</title><main>Page B</main>");
  778. } else if (request.url === "/iframe-parent") {
  779. response.end(
  780. '<!doctype html><title>Iframe parent</title><iframe src="/iframe-child"></iframe>',
  781. );
  782. } else if (request.url === "/iframe-child") {
  783. response.end(
  784. "<!doctype html><title>Iframe child</title><main data-e2e-child>child loaded</main>",
  785. );
  786. } else {
  787. response.writeHead(404);
  788. response.end();
  789. }
  790. });
  791. }
  792. async function listen(fixtureServer: Server): Promise<string> {
  793. await new Promise<void>((resolve, reject) => {
  794. fixtureServer.once("error", reject);
  795. fixtureServer.listen(0, "127.0.0.1", () => {
  796. fixtureServer.off("error", reject);
  797. resolve();
  798. });
  799. });
  800. const address = fixtureServer.address();
  801. if (!address || typeof address === "string") throw new Error("最近访问 fixture 未绑定端口");
  802. return `http://127.0.0.1:${address.port}`;
  803. }