browserSettingsSection.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import { beforeEach, describe, expect, it, vi } from "vitest";
  4. import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  5. const h = vi.hoisted(() => {
  6. const importChromeBrowserData = vi.fn(async () => ({
  7. success: true,
  8. cookies: { imported: 3, skipped: 1, failed: 0 },
  9. localStorage: {
  10. originsImported: 1,
  11. entriesImported: 2,
  12. originsSkipped: 0,
  13. originsFailed: 0,
  14. },
  15. }));
  16. const clearEmbeddedBrowserData = vi.fn(async () => ({ success: true }));
  17. const initialize = vi.fn(async () => {});
  18. const setEnabled = vi.fn(async (_pluginId: string, enabled: boolean) => {
  19. pluginState.plugins[0].enabled = enabled;
  20. });
  21. const pluginState = {
  22. plugins: [
  23. {
  24. id: "browser-use@zcode-plugins-official",
  25. name: "browser-use",
  26. enabled: true,
  27. },
  28. ],
  29. loading: false,
  30. error: null as string | null,
  31. togglingPluginId: null as string | null,
  32. initialize,
  33. setEnabled,
  34. };
  35. return {
  36. clearEmbeddedBrowserData,
  37. importChromeBrowserData,
  38. initialize,
  39. pluginState,
  40. setEnabled,
  41. };
  42. });
  43. vi.mock("@/hooks/usePlatform.js", () => ({
  44. usePlatform: () => ({
  45. importChromeBrowserData: h.importChromeBrowserData,
  46. clearEmbeddedBrowserData: h.clearEmbeddedBrowserData,
  47. }),
  48. }));
  49. vi.mock("@/hooks/useServices.js", () => ({
  50. useServices: () => ({
  51. pluginManagementService: {},
  52. skillsService: {},
  53. }),
  54. }));
  55. vi.mock("@/hooks/useZCodeSessionService.js", () => ({
  56. useZCodeSessionService: () => ({}),
  57. }));
  58. vi.mock("@/i18n/IntlProvider.js", () => ({
  59. useZCodeIntl: () => ({
  60. intl: {
  61. formatMessage: ({ id }: { id: string }) => id,
  62. },
  63. }),
  64. }));
  65. vi.mock("@/lib/zcodeDraftSkillInvalidation.js", () => ({
  66. invalidateDeferredDraftSessionForSkillChange: vi.fn(async () => {}),
  67. }));
  68. vi.mock("@/store/pluginManagementStore.js", () => ({
  69. usePluginManagementStore: Object.assign(
  70. (selector: (state: typeof h.pluginState) => unknown) => selector(h.pluginState),
  71. { getState: () => h.pluginState },
  72. ),
  73. }));
  74. vi.mock("@/store/skillStore.js", () => ({
  75. useSkillStore: (selector: (state: Record<string, unknown>) => unknown) =>
  76. selector({
  77. refresh: vi.fn(async () => {}),
  78. workspacePath: null,
  79. workspaceIdentity: null,
  80. }),
  81. }));
  82. vi.mock("@/components/ui/toast.js", () => ({ toast: vi.fn() }));
  83. import { BrowserSettingsSection } from "@/settings/BrowserSettingsSection.js";
  84. beforeEach(() => {
  85. cleanup();
  86. vi.clearAllMocks();
  87. h.pluginState.plugins[0].enabled = true;
  88. h.pluginState.loading = false;
  89. h.pluginState.error = null;
  90. h.pluginState.togglingPluginId = null;
  91. });
  92. function renderSection(
  93. isDesktop = true,
  94. isWindowsDesktop = false,
  95. overrides: Record<string, unknown> = {},
  96. ) {
  97. return render(
  98. createElement(BrowserSettingsSection, {
  99. isDesktop,
  100. isWindowsDesktop,
  101. workspacePath: "/workspace",
  102. workspaceIdentity: "workspace-id",
  103. ...overrides,
  104. }),
  105. );
  106. }
  107. describe("BrowserSettingsSection", () => {
  108. it("展示忽略证书校验开关,默认关闭并把用户选择回传保存", () => {
  109. const onChange = vi.fn(async () => {});
  110. renderSection(true, false, {
  111. embeddedBrowserAllowInsecureCertificates: false,
  112. onEmbeddedBrowserAllowInsecureCertificatesChange: onChange,
  113. });
  114. const toggle = screen.getByRole("switch", {
  115. name: "settings.embeddedBrowserAllowInsecureCertificates",
  116. });
  117. // 降低安全性的开关必须默认关闭,用户升级新版本不能被动获得放行行为。
  118. expect(toggle.getAttribute("aria-checked")).toBe("false");
  119. fireEvent.click(toggle);
  120. expect(onChange).toHaveBeenCalledWith(true);
  121. });
  122. it("开关已开启时反映选中态", () => {
  123. renderSection(true, false, {
  124. embeddedBrowserAllowInsecureCertificates: true,
  125. onEmbeddedBrowserAllowInsecureCertificatesChange: vi.fn(async () => {}),
  126. });
  127. expect(
  128. screen
  129. .getByRole("switch", { name: "settings.embeddedBrowserAllowInsecureCertificates" })
  130. .getAttribute("aria-checked"),
  131. ).toBe("true");
  132. });
  133. it("非桌面端不展示忽略证书校验开关", () => {
  134. renderSection(false, false, {
  135. embeddedBrowserAllowInsecureCertificates: false,
  136. onEmbeddedBrowserAllowInsecureCertificatesChange: vi.fn(async () => {}),
  137. });
  138. expect(
  139. screen.queryByRole("switch", {
  140. name: "settings.embeddedBrowserAllowInsecureCertificates",
  141. }),
  142. ).toBeNull();
  143. });
  144. it("浏览器数据操作按钮与 Terminal font 操作控件使用一致的 lg 尺寸", () => {
  145. renderSection();
  146. for (const name of [
  147. "settings.browser.import.action",
  148. "settings.browser.clearCache.action",
  149. "settings.browser.clearAll.action",
  150. ]) {
  151. const button = screen.getByRole("button", { name });
  152. expect(button.className).toContain("h-8");
  153. expect(button.className).toContain("rounded-lg");
  154. expect(button.getAttribute("data-size")).toBe("lg");
  155. }
  156. });
  157. it("BS-037 导入登录状态与内置浏览器控制开关同卡片,且排在开关之后", () => {
  158. renderSection();
  159. const controlSwitch = screen.getByRole("switch", { name: "settings.browser.control.title" });
  160. const importButton = screen.getByRole("button", { name: "settings.browser.import.action" });
  161. const controlCard = controlSwitch.closest('[data-slot="card"]');
  162. // 断言前先确认取到了卡片容器,避免 closest 返回 null 时后续断言退化成永真
  163. expect(controlCard).not.toBeNull();
  164. // 导入登录状态是"开启内置浏览器控制"之后的配套动作,同卡片才能表达先后关系
  165. expect(controlCard?.contains(importButton)).toBe(true);
  166. expect(
  167. controlSwitch.compareDocumentPosition(importButton) & Node.DOCUMENT_POSITION_FOLLOWING,
  168. ).toBeTruthy();
  169. });
  170. it("BS-037 浏览器数据分组只保留清除类操作", () => {
  171. renderSection();
  172. const clearCacheButton = screen.getByRole("button", {
  173. name: "settings.browser.clearCache.action",
  174. });
  175. const importButton = screen.getByRole("button", { name: "settings.browser.import.action" });
  176. const dataCard = clearCacheButton.closest('[data-slot="card"]');
  177. expect(dataCard).not.toBeNull();
  178. expect(dataCard?.contains(importButton)).toBe(false);
  179. expect(
  180. dataCard?.contains(screen.getByRole("button", { name: "settings.browser.clearAll.action" })),
  181. ).toBe(true);
  182. });
  183. it("复用官方 browser-use plugin 开关并初始化当前 workspace", async () => {
  184. renderSection();
  185. expect(h.initialize).toHaveBeenCalledWith(
  186. expect.objectContaining({
  187. workspacePath: "/workspace",
  188. workspaceIdentity: "workspace-id",
  189. }),
  190. );
  191. fireEvent.click(screen.getByRole("switch", { name: "settings.browser.control.title" }));
  192. await waitFor(() => {
  193. expect(h.setEnabled).toHaveBeenCalledWith(
  194. "browser-use@zcode-plugins-official",
  195. false,
  196. expect.anything(),
  197. );
  198. });
  199. });
  200. it("桌面端一键导入 Chrome 当前 Profile 的 Cookie 与 LocalStorage", async () => {
  201. renderSection();
  202. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  203. await waitFor(() => {
  204. expect(h.importChromeBrowserData).toHaveBeenCalledOnce();
  205. });
  206. expect(await screen.findByText("settings.browser.import.success")).toBeTruthy();
  207. });
  208. it("Windows 暂时隐藏导入入口但保留浏览器数据清理", () => {
  209. renderSection(true, true);
  210. expect(screen.queryByRole("button", { name: "settings.browser.import.action" })).toBeNull();
  211. expect(
  212. screen.getByRole("button", { name: "settings.browser.clearCache.action" }),
  213. ).toBeTruthy();
  214. expect(screen.getByRole("button", { name: "settings.browser.clearAll.action" })).toBeTruthy();
  215. expect(
  216. screen.queryByRole("checkbox", { name: "settings.browser.import.adminConsent" }),
  217. ).toBeNull();
  218. expect(h.importChromeBrowserData).not.toHaveBeenCalled();
  219. });
  220. it("未安装 Chrome 时展示 Chrome 未找到提示", async () => {
  221. h.importChromeBrowserData.mockResolvedValueOnce({
  222. success: false,
  223. cookies: { imported: 0, skipped: 0, failed: 0 },
  224. localStorage: {
  225. originsImported: 0,
  226. entriesImported: 0,
  227. originsSkipped: 0,
  228. originsFailed: 0,
  229. },
  230. error: "chrome_executable_not_found",
  231. });
  232. renderSection();
  233. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  234. expect(await screen.findByText("settings.browser.import.executableNotFound")).toBeTruthy();
  235. });
  236. it("Profile 无法自动消歧时展示可操作错误", async () => {
  237. h.importChromeBrowserData.mockResolvedValueOnce({
  238. success: false,
  239. cookies: { imported: 0, skipped: 0, failed: 0 },
  240. localStorage: {
  241. originsImported: 0,
  242. entriesImported: 0,
  243. originsSkipped: 0,
  244. originsFailed: 0,
  245. },
  246. error: "chrome_profile_ambiguous",
  247. });
  248. renderSection();
  249. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  250. expect(await screen.findByText("settings.browser.import.ambiguous")).toBeTruthy();
  251. });
  252. it("macOS 钥匙串授权被拒绝时提示导入已取消", async () => {
  253. h.importChromeBrowserData.mockResolvedValueOnce({
  254. success: false,
  255. cookies: { imported: 0, skipped: 0, failed: 0 },
  256. localStorage: {
  257. originsImported: 0,
  258. entriesImported: 0,
  259. originsSkipped: 0,
  260. originsFailed: 0,
  261. },
  262. error: "chrome_cookie_access_denied",
  263. });
  264. renderSection();
  265. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  266. expect(await screen.findByText("settings.browser.import.accessDenied")).toBeTruthy();
  267. });
  268. it("部分 Cookie 未导入时只展示实际导入数量", async () => {
  269. h.importChromeBrowserData.mockResolvedValueOnce({
  270. success: true,
  271. cookies: { imported: 2, skipped: 4, failed: 0 },
  272. localStorage: {
  273. originsImported: 1,
  274. entriesImported: 3,
  275. originsSkipped: 0,
  276. originsFailed: 0,
  277. },
  278. issues: ["chrome_cookie_protection_unsupported"],
  279. });
  280. renderSection();
  281. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  282. expect(await screen.findByText("settings.browser.import.success")).toBeTruthy();
  283. expect(screen.queryByText("settings.browser.import.partialCookieProtected")).toBeNull();
  284. expect(screen.queryByText("settings.browser.import.successWithSkipped")).toBeNull();
  285. });
  286. it("Web/手机端禁用本机浏览器数据操作并展示桌面端提示", () => {
  287. renderSection(false);
  288. expect(screen.getByText("settings.browser.desktopOnly")).toBeTruthy();
  289. expect(
  290. (
  291. screen.getByRole("button", {
  292. name: "settings.browser.import.action",
  293. }) as HTMLButtonElement
  294. ).disabled,
  295. ).toBe(true);
  296. expect(
  297. (
  298. screen.getByRole("button", {
  299. name: "settings.browser.clearCache.action",
  300. }) as HTMLButtonElement
  301. ).disabled,
  302. ).toBe(true);
  303. });
  304. });