browserSettingsSection.test.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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("复用官方 browser-use plugin 开关并初始化当前 workspace", async () => {
  145. renderSection();
  146. expect(h.initialize).toHaveBeenCalledWith(
  147. expect.objectContaining({
  148. workspacePath: "/workspace",
  149. workspaceIdentity: "workspace-id",
  150. }),
  151. );
  152. fireEvent.click(screen.getByRole("switch", { name: "settings.browser.control.title" }));
  153. await waitFor(() => {
  154. expect(h.setEnabled).toHaveBeenCalledWith(
  155. "browser-use@zcode-plugins-official",
  156. false,
  157. expect.anything(),
  158. );
  159. });
  160. });
  161. it("桌面端一键导入 Chrome 当前 Profile 的 Cookie 与 LocalStorage", async () => {
  162. renderSection();
  163. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  164. await waitFor(() => {
  165. expect(h.importChromeBrowserData).toHaveBeenCalledOnce();
  166. });
  167. expect(await screen.findByText("settings.browser.import.success")).toBeTruthy();
  168. });
  169. it("Windows 暂时隐藏导入入口但保留浏览器数据清理", () => {
  170. renderSection(true, true);
  171. expect(screen.queryByRole("button", { name: "settings.browser.import.action" })).toBeNull();
  172. expect(screen.getByRole("button", { name: "settings.browser.clearCache.action" })).toBeTruthy();
  173. expect(screen.getByRole("button", { name: "settings.browser.clearAll.action" })).toBeTruthy();
  174. expect(
  175. screen.queryByRole("checkbox", { name: "settings.browser.import.adminConsent" }),
  176. ).toBeNull();
  177. expect(h.importChromeBrowserData).not.toHaveBeenCalled();
  178. });
  179. it("未安装 Chrome 时展示 Chrome 未找到提示", async () => {
  180. h.importChromeBrowserData.mockResolvedValueOnce({
  181. success: false,
  182. cookies: { imported: 0, skipped: 0, failed: 0 },
  183. localStorage: {
  184. originsImported: 0,
  185. entriesImported: 0,
  186. originsSkipped: 0,
  187. originsFailed: 0,
  188. },
  189. error: "chrome_executable_not_found",
  190. });
  191. renderSection();
  192. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  193. expect(await screen.findByText("settings.browser.import.executableNotFound")).toBeTruthy();
  194. });
  195. it("Profile 无法自动消歧时展示可操作错误", async () => {
  196. h.importChromeBrowserData.mockResolvedValueOnce({
  197. success: false,
  198. cookies: { imported: 0, skipped: 0, failed: 0 },
  199. localStorage: {
  200. originsImported: 0,
  201. entriesImported: 0,
  202. originsSkipped: 0,
  203. originsFailed: 0,
  204. },
  205. error: "chrome_profile_ambiguous",
  206. });
  207. renderSection();
  208. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  209. expect(await screen.findByText("settings.browser.import.ambiguous")).toBeTruthy();
  210. });
  211. it("macOS 钥匙串授权被拒绝时提示导入已取消", async () => {
  212. h.importChromeBrowserData.mockResolvedValueOnce({
  213. success: false,
  214. cookies: { imported: 0, skipped: 0, failed: 0 },
  215. localStorage: {
  216. originsImported: 0,
  217. entriesImported: 0,
  218. originsSkipped: 0,
  219. originsFailed: 0,
  220. },
  221. error: "chrome_cookie_access_denied",
  222. });
  223. renderSection();
  224. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  225. expect(await screen.findByText("settings.browser.import.accessDenied")).toBeTruthy();
  226. });
  227. it("部分 Cookie 未导入时只展示实际导入数量", async () => {
  228. h.importChromeBrowserData.mockResolvedValueOnce({
  229. success: true,
  230. cookies: { imported: 2, skipped: 4, failed: 0 },
  231. localStorage: {
  232. originsImported: 1,
  233. entriesImported: 3,
  234. originsSkipped: 0,
  235. originsFailed: 0,
  236. },
  237. issues: ["chrome_cookie_protection_unsupported"],
  238. });
  239. renderSection();
  240. fireEvent.click(screen.getByRole("button", { name: "settings.browser.import.action" }));
  241. expect(await screen.findByText("settings.browser.import.success")).toBeTruthy();
  242. expect(screen.queryByText("settings.browser.import.partialCookieProtected")).toBeNull();
  243. expect(screen.queryByText("settings.browser.import.successWithSkipped")).toBeNull();
  244. });
  245. it("Web/手机端禁用本机浏览器数据操作并展示桌面端提示", () => {
  246. renderSection(false);
  247. expect(screen.getByText("settings.browser.desktopOnly")).toBeTruthy();
  248. expect(
  249. (
  250. screen.getByRole("button", {
  251. name: "settings.browser.import.action",
  252. }) as HTMLButtonElement
  253. ).disabled,
  254. ).toBe(true);
  255. expect(
  256. (
  257. screen.getByRole("button", {
  258. name: "settings.browser.clearCache.action",
  259. }) as HTMLButtonElement
  260. ).disabled,
  261. ).toBe(true);
  262. });
  263. });