codingPlanEmbeddedWebview.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import { cleanup, render } from "@testing-library/react";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { readFileSync } from "node:fs";
  6. import { resolve } from "node:path";
  7. import {
  8. BUILTIN_MODEL_PROVIDER_IDS,
  9. DEFAULT_ZCODE_ENDPOINT_ORIGIN,
  10. isTrustedCodingPlanWebviewOrigin,
  11. } from "@zcode/shared";
  12. import { CodingPlanWebviewChannels, type CodingPlanPurchaseCompletePayload } from "@zcode/shared";
  13. import {
  14. buildCodingPlanEmbeddedWebviewUrl,
  15. buildCodingPlanEmbeddedReportContext,
  16. createCodingPlanAuthInjectionScript,
  17. createCodingPlanCredentialClearScript,
  18. createCodingPlanScrollbarHideScript,
  19. getCodingPlanCredentialKeys,
  20. isTrustedCodingPlanEmbeddedWebviewUrl,
  21. resolveCodingPlanEmbeddedOrigin,
  22. resolveCodingPlanWebsiteProvider,
  23. } from "@/settings/model-provider-section/codingPlanEmbeddedWebview.js";
  24. import { CodingPlanEmbeddedWebviewDialog } from "@/settings/CodingPlanEmbeddedWebviewDialog.js";
  25. const h = vi.hoisted(() => ({
  26. theme: "zai-light",
  27. }));
  28. vi.mock("@/hooks/usePlatform.js", () => ({
  29. usePlatform: () => ({
  30. activateOrSetWorkspace: vi.fn(),
  31. connectRemote: vi.fn(),
  32. getDeviceId: vi.fn(() => Promise.resolve("device-mid-test")),
  33. notifyRendererReady: vi.fn(),
  34. onOAuthCallback: vi.fn(),
  35. openExternal: vi.fn(),
  36. registerOAuthState: vi.fn(),
  37. selectDirectory: vi.fn(),
  38. }),
  39. }));
  40. vi.mock("@/i18n/IntlProvider.js", () => ({
  41. useZCodeIntl: () => ({
  42. intl: {
  43. formatMessage: ({ id }: { id: string }) => id,
  44. },
  45. locale: "en-US",
  46. }),
  47. }));
  48. vi.mock("@/store/StoreProvider.js", () => ({
  49. useZCodeStoreWithDefault: (
  50. selector: (state: { theme: string; user: { id: string } | null }) => unknown,
  51. ) =>
  52. selector({
  53. theme: h.theme,
  54. user: { id: "user-test" },
  55. }),
  56. }));
  57. afterEach(() => {
  58. cleanup();
  59. h.theme = "zai-light";
  60. });
  61. describe("coding plan embedded webview bridge", () => {
  62. it("exports the embedded dialog component", () => {
  63. expect(CodingPlanEmbeddedWebviewDialog).toBeTypeOf("function");
  64. });
  65. it("exposes the purchase-complete channel and payload type", () => {
  66. // 频道名固定,两端(App preload + 官网通过注入的 bridge)共享
  67. expect(CodingPlanWebviewChannels.PurchaseComplete).toBe("zcode:coding-plan-purchase-complete");
  68. // payload 类型仅做编译期校验:provider 限定 zai/bigmodel,timestamp 为 number
  69. const payload: CodingPlanPurchaseCompletePayload = {
  70. provider: "zai",
  71. timestamp: Date.now(),
  72. };
  73. expect(payload.provider).toBe("zai");
  74. expect(typeof payload.timestamp).toBe("number");
  75. });
  76. it("builds the website URL with app embedded marker and no telemetry query", () => {
  77. const url = new URL(
  78. buildCodingPlanEmbeddedWebviewUrl({
  79. origin: "https://zcode.z.ai",
  80. provider: "bigmodel",
  81. audience: "team",
  82. teamPlanKey: "team-plan-a",
  83. theme: "zai-light",
  84. }),
  85. );
  86. expect(url.origin).toBe("https://zcode.z.ai");
  87. expect(url.pathname).toBe("/coding-plan");
  88. expect(Object.fromEntries(url.searchParams)).toMatchObject({
  89. provider: "bigmodel",
  90. embedded: "app",
  91. lang: "en",
  92. theme: "zai-light",
  93. audience: "team",
  94. teamPlanKey: "team-plan-a",
  95. });
  96. expect(url.searchParams.has("purchase_funnel_id")).toBe(false);
  97. expect(url.searchParams.has("device_mid")).toBe(false);
  98. expect(url.searchParams.has("user_id")).toBe(false);
  99. expect(url.searchParams.has("app_version")).toBe(false);
  100. });
  101. it.each([
  102. [BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan, "zai"],
  103. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan, "bigmodel"],
  104. ] as const)("maps Team Provider %s to website family %s", (providerId, family) => {
  105. expect(resolveCodingPlanWebsiteProvider(providerId)).toBe(family);
  106. });
  107. it("builds the report context that website telemetry reads from the bridge", () => {
  108. expect(
  109. buildCodingPlanEmbeddedReportContext({
  110. deviceMid: "device-mid-test",
  111. userId: "user-1",
  112. appVersion: "9.8.7",
  113. funnelContext: {
  114. purchaseFunnelId: "funnel-app",
  115. upgradeSource: "session_quota_alert",
  116. eventRegion: "app.session",
  117. eventText: "upgrade",
  118. entryPlanStatus: "start_plan",
  119. entryPlanLevel: "start",
  120. entryPlanList: "start_plan__weekend-plan",
  121. purchaseAudience: "team",
  122. providerFamily: "bigmodel",
  123. channel: "MaaS",
  124. },
  125. }),
  126. ).toMatchObject({
  127. purchase_funnel_id: "funnel-app",
  128. purchase_entry_reporter: "app",
  129. upgrade_source: "session_quota_alert",
  130. event_region: "app.session",
  131. event_text: "upgrade",
  132. entry_plan_status: "start_plan",
  133. entry_plan_level: "start",
  134. purchase_audience: "team",
  135. provider_family: "bigmodel",
  136. channel: "MaaS",
  137. device_mid: "device-mid-test",
  138. user_id: "user-1",
  139. app_version: "9.8.7",
  140. });
  141. });
  142. it("does not claim app entry reporting without a funnel", () => {
  143. expect(buildCodingPlanEmbeddedReportContext({})).not.toHaveProperty("purchase_entry_reporter");
  144. });
  145. it("preserves entry ownership in window, storage and ready events on reinjection", () => {
  146. const ready = vi.fn();
  147. window.addEventListener("zcode-coding-plan-auth-ready", ready);
  148. try {
  149. const reportContext = {
  150. purchase_funnel_id: "funnel-app",
  151. purchase_entry_reporter: "app" as const,
  152. };
  153. const script = createCodingPlanAuthInjectionScript({
  154. provider: "bigmodel",
  155. credentials: {},
  156. reportContext,
  157. });
  158. window.eval(script);
  159. window.eval(script);
  160. expect(
  161. (window as unknown as { __zcodeReportContext__: unknown }).__zcodeReportContext__,
  162. ).toEqual(reportContext);
  163. expect(JSON.parse(localStorage.getItem("zcode:coding-plan:report-context") || "{}")).toEqual(
  164. reportContext,
  165. );
  166. expect(ready).toHaveBeenCalledTimes(2);
  167. for (const [event] of ready.mock.calls) {
  168. expect((event as CustomEvent).detail.reportContext).toEqual(reportContext);
  169. }
  170. } finally {
  171. window.removeEventListener("zcode-coding-plan-auth-ready", ready);
  172. window.eval(createCodingPlanCredentialClearScript());
  173. }
  174. });
  175. it("uses localhost in local development and endpoint origin otherwise", () => {
  176. expect(
  177. resolveCodingPlanEmbeddedOrigin({
  178. dev: true,
  179. endpointOrigin: "https://zcode.z.ai",
  180. zcodeEnv: "test",
  181. }),
  182. ).toBe("http://localhost:3000");
  183. expect(
  184. resolveCodingPlanEmbeddedOrigin({
  185. dev: true,
  186. endpointOrigin: "https://zcode.z.ai",
  187. zcodeEnv: "production",
  188. }),
  189. ).toBe("https://zcode.z.ai");
  190. expect(
  191. resolveCodingPlanEmbeddedOrigin({
  192. dev: false,
  193. endpointOrigin: "https://zcode.z.ai",
  194. zcodeEnv: "production",
  195. }),
  196. ).toBe("https://zcode.z.ai");
  197. expect(
  198. resolveCodingPlanEmbeddedOrigin({
  199. dev: true,
  200. endpointOrigin: "https://zcode.z.ai",
  201. zcodeEnv: "test",
  202. overrideOrigin: "https://example.test/path",
  203. }),
  204. ).toBe("http://localhost:3000");
  205. });
  206. it("only trusts official coding plan origins unless the E2E bridge enables loopback mocks", () => {
  207. expect(isTrustedCodingPlanWebviewOrigin("https://zcode.z.ai")).toBe(true);
  208. expect(isTrustedCodingPlanWebviewOrigin("https://zcode.z.ai")).toBe(true);
  209. expect(isTrustedCodingPlanWebviewOrigin("http://localhost:3000")).toBe(true);
  210. expect(isTrustedCodingPlanWebviewOrigin("https://evil.example")).toBe(false);
  211. expect(isTrustedCodingPlanWebviewOrigin("http://127.0.0.1:4555")).toBe(false);
  212. expect(
  213. isTrustedCodingPlanWebviewOrigin("http://127.0.0.1:4555", {
  214. e2eStoreBridgeEnabled: true,
  215. }),
  216. ).toBe(true);
  217. });
  218. it("trusts PayPal callback pages that return to the embedded Coding Plan page", () => {
  219. const returnTo = encodeURIComponent(
  220. "/coding-plan?provider=zai&embedded=app&lang=cn&theme=zai-dark",
  221. );
  222. expect(
  223. isTrustedCodingPlanEmbeddedWebviewUrl(
  224. `http://localhost:3000/coding-plan/payment/callback?channel=paypal&status=return&returnTo=${returnTo}`,
  225. ),
  226. ).toBe(true);
  227. expect(
  228. isTrustedCodingPlanEmbeddedWebviewUrl(
  229. "http://localhost:3000/coding-plan/payment/callback?channel=paypal&status=return",
  230. ),
  231. ).toBe(false);
  232. expect(
  233. isTrustedCodingPlanEmbeddedWebviewUrl(
  234. "http://localhost:3000/coding-plan/payment/callback?returnTo=%2Fcoding-plan%3Fprovider%3Dzai",
  235. ),
  236. ).toBe(false);
  237. });
  238. it("falls back to the official website when a configured webview override is not trusted", () => {
  239. expect(
  240. resolveCodingPlanEmbeddedOrigin({
  241. dev: false,
  242. endpointOrigin: "https://untrusted.example",
  243. overrideOrigin: "https://evil.example/path",
  244. }),
  245. ).toBe(DEFAULT_ZCODE_ENDPOINT_ORIGIN);
  246. expect(
  247. resolveCodingPlanEmbeddedOrigin({
  248. dev: false,
  249. endpointOrigin: "https://untrusted.example",
  250. e2eStoreBridgeEnabled: true,
  251. overrideOrigin: "http://127.0.0.1:4555/path",
  252. }),
  253. ).toBe("http://127.0.0.1:4555");
  254. });
  255. it("maps coding plan provider ids to website provider query values", () => {
  256. expect(
  257. resolveCodingPlanWebsiteProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  258. ).toBe("zai");
  259. expect(resolveCodingPlanWebsiteProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan)).toBe("zai");
  260. expect(
  261. resolveCodingPlanWebsiteProvider(BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan),
  262. ).toBe("bigmodel");
  263. });
  264. it("injects provider credentials into the webview localStorage and dispatches ready event", () => {
  265. const script = createCodingPlanAuthInjectionScript({
  266. provider: "zai",
  267. theme: "zai-dark",
  268. locale: "en-US",
  269. credentials: {
  270. zaiAccessToken: "zai-business-token",
  271. zcodeJwtToken: "zcode-jwt",
  272. },
  273. reportContext: {
  274. purchase_funnel_id: "funnel-app",
  275. device_mid: "device-mid-test",
  276. user_id: "user-1",
  277. app_version: "9.8.7",
  278. },
  279. });
  280. expect(script).toContain('localStorage.setItem("oauth:zai:access_token"');
  281. expect(script).toContain('localStorage.setItem("zcodejwttoken"');
  282. expect(script).toContain("zcode-coding-plan-auth-ready");
  283. expect(script).toContain('"provider":"zai"');
  284. expect(script).toContain("window.__zcodeReportContext__");
  285. expect(script).toContain("zcode:coding-plan:report-context");
  286. expect(script).toContain('"purchase_funnel_id":"funnel-app"');
  287. expect(script).toContain('"device_mid":"device-mid-test"');
  288. expect(script).toContain('"user_id":"user-1"');
  289. expect(script).toContain('"app_version":"9.8.7"');
  290. expect(script).toContain("reportContext: zcodeReportContext");
  291. expect(script).toContain('document.documentElement.classList.toggle("dark"');
  292. expect(script).toContain('localStorage.setItem("zcode-theme", zcodeTheme)');
  293. expect(script).toContain('localStorage.removeItem("oauth:bigmodel:access_token")');
  294. });
  295. it("injects the zcode JWT for the bigmodel provider so the website can query Start Plan balance", () => {
  296. // 修复原因:BigModel 分支此前显式清空 zcodejwttoken,官网内嵌页查不到
  297. // billing/balance(该接口只认 zcode JWT),Start Plan 卡被误判为「已过期」。
  298. const script = createCodingPlanAuthInjectionScript({
  299. provider: "bigmodel",
  300. theme: "zai-light",
  301. locale: "zh-CN",
  302. credentials: {
  303. bigmodelAccessToken: "bigmodel-business-token",
  304. zcodeJwtToken: "zcode-jwt",
  305. },
  306. });
  307. expect(script).toContain('localStorage.setItem("oauth:bigmodel:access_token"');
  308. expect(script).toContain('localStorage.setItem("zcodejwttoken"');
  309. expect(script).toContain('localStorage.removeItem("oauth:zai:access_token")');
  310. });
  311. it("loads the zcode JWT credential key for both website providers", () => {
  312. expect(getCodingPlanCredentialKeys("zai")).toEqual([
  313. "oauth:zai:access_token",
  314. "zcodejwttoken",
  315. ]);
  316. expect(getCodingPlanCredentialKeys("bigmodel")).toEqual([
  317. "oauth:bigmodel:access_token",
  318. "zcodejwttoken",
  319. ]);
  320. });
  321. it("clears all provider credential keys from the persistent webview storage", () => {
  322. const script = createCodingPlanCredentialClearScript();
  323. expect(script).toContain("oauth:zai:access_token");
  324. expect(script).toContain("zcodejwttoken");
  325. expect(script).toContain("oauth:bigmodel:access_token");
  326. expect(script).toContain("localStorage.removeItem(key)");
  327. expect(script).toContain("zcode:coding-plan:report-context");
  328. expect(script).toContain("delete window.__zcodeReportContext__");
  329. });
  330. it("injects a guest-page scrollbar hiding style without disabling scroll", () => {
  331. const script = createCodingPlanScrollbarHideScript();
  332. expect(script).toContain("zcode-coding-plan-hide-scrollbar");
  333. expect(script).toContain("scrollbar-width: none");
  334. expect(script).toContain("::-webkit-scrollbar");
  335. expect(script).toContain("display: none");
  336. expect(script).not.toContain("overflow: hidden");
  337. });
  338. it("only injects credentials on the current trusted embedded coding plan page", () => {
  339. expect(
  340. isTrustedCodingPlanEmbeddedWebviewUrl(
  341. "https://zcode.z.ai/coding-plan?provider=zai&embedded=app",
  342. ),
  343. ).toBe(true);
  344. expect(
  345. isTrustedCodingPlanEmbeddedWebviewUrl(
  346. "https://zcode.z.ai/cn/coding-plan?provider=zai&embedded=app",
  347. ),
  348. ).toBe(true);
  349. expect(isTrustedCodingPlanEmbeddedWebviewUrl("https://pay.example/checkout?embedded=app")).toBe(
  350. false,
  351. );
  352. expect(
  353. isTrustedCodingPlanEmbeddedWebviewUrl("https://zcode.z.ai/coding-plan?provider=zai"),
  354. ).toBe(false);
  355. });
  356. it("wires the upgrade dialog to the embedded website dialog", () => {
  357. const source = readFileSync(
  358. resolve("packages/ui/src/settings/CodingPlanUpgradeDialog.tsx"),
  359. "utf8",
  360. );
  361. expect(source).toContain("CodingPlanEmbeddedWebviewDialog");
  362. expect(source).not.toContain("<CodingPlanPurchasePanel");
  363. });
  364. it("keeps the app-style full-screen shell without the host billing discount banner", () => {
  365. const source = readFileSync(
  366. resolve("packages/ui/src/settings/CodingPlanEmbeddedWebviewDialog.tsx"),
  367. "utf8",
  368. );
  369. expect(source).toContain("fixed inset-0 z-50 flex flex-col");
  370. expect(source).toContain("bg-background pt-12 text-foreground");
  371. expect(source).toContain("overflow-y-auto");
  372. expect(source).toContain(
  373. "mx-auto flex w-full flex-1 flex-col px-6 pt-2 pb-8 max-sm:px-4 max-sm:pt-2 max-sm:pb-5",
  374. );
  375. expect(source).toContain("settings.modelProvider.codingPlan.webview.title");
  376. expect(source).not.toContain("CodingPlanBillingDiscountBanner");
  377. expect(source).not.toContain("useCodingPlanBillingDiscount");
  378. expect(source).toContain("<EmbeddedWebsiteHeader");
  379. expect(source).toContain("onClose={() => onOpenChange(false)}");
  380. expect(readFileSync(resolve("packages/ui/src/components/EmbeddedWebsiteHeader.tsx"), "utf8")).toContain("common.close");
  381. expect(source).toContain("webviewCleanupRef");
  382. expect(source).toContain("injectAuthRef");
  383. expect(source).toContain("createCodingPlanCredentialClearScript");
  384. expect(source).toContain("createCodingPlanScrollbarHideScript");
  385. expect(source).toContain("theme: embeddedTheme");
  386. expect(source).toContain('addEventListener("dom-ready"');
  387. expect(source).not.toContain("webview.isLoading");
  388. });
  389. it("adds host navigation controls for third-party payment pages", () => {
  390. const source = readFileSync(
  391. resolve("packages/ui/src/settings/CodingPlanEmbeddedWebviewDialog.tsx"),
  392. "utf8",
  393. );
  394. // 三方支付页进入 webview 后没有 App 顶部导航,宿主需要暴露后退/前进/刷新控件。
  395. expect(source).toContain("navigationState");
  396. expect(source).toContain("handleGoBack");
  397. expect(source).toContain("handleGoForward");
  398. expect(source).toContain("handleReloadWebview");
  399. expect(source).toContain("webview.canGoBack()");
  400. expect(source).toContain("webview.canGoForward()");
  401. expect(source).toContain("webview.goBack()");
  402. expect(source).toContain("webview.goForward()");
  403. expect(source).toContain('addEventListener("did-stop-loading"');
  404. expect(source).toContain('addEventListener("did-navigate"');
  405. expect(source).toContain('addEventListener("did-navigate-in-page"');
  406. const header = readFileSync(resolve("packages/ui/src/components/EmbeddedWebsiteHeader.tsx"), "utf8");
  407. expect(source).toContain("onBack={handleGoBack}");
  408. expect(source).toContain("onForward={handleGoForward}");
  409. expect(source).toContain("onReload={handleReloadWebview}");
  410. expect(header).toContain("quickPick.command.goBack");
  411. expect(header).toContain("quickPick.command.goForward");
  412. expect(header).toContain("common.refresh");
  413. });
  414. it("listens for did-fail-load and render-process-gone to surface webview failures", () => {
  415. const source = readFileSync(
  416. resolve("packages/ui/src/settings/CodingPlanEmbeddedWebviewDialog.tsx"),
  417. "utf8",
  418. );
  419. // 改造原因:webview 加载失败/崩溃时,按用户决策只报错并引导去官网,不回退到老 Dialog。
  420. expect(source).toContain('addEventListener("did-fail-load"');
  421. expect(source).toContain('addEventListener("render-process-gone"');
  422. expect(source).toContain("handleDidFailLoad");
  423. expect(source).toContain("handleRenderProcessGone");
  424. expect(source).toContain("setLoadError");
  425. });
  426. it("shows the load-failure fallback with an open-website action when the webview fails", () => {
  427. const source = readFileSync(
  428. resolve("packages/ui/src/settings/CodingPlanEmbeddedWebviewDialog.tsx"),
  429. "utf8",
  430. );
  431. expect(source).toContain("settings.modelProvider.codingPlan.webview.loadFailed");
  432. expect(source).toContain("settings.modelProvider.codingPlan.webview.openWebsite");
  433. // 前往官网购买:通过 IPlatformService.openExternal 打开官网页
  434. expect(source).toContain("usePlatform");
  435. expect(source).toContain("platform.openExternal");
  436. expect(source).toContain("handleOpenWebsite");
  437. });
  438. it("hides the webview element while a load error is visible", () => {
  439. const source = readFileSync(
  440. resolve("packages/ui/src/settings/CodingPlanEmbeddedWebviewDialog.tsx"),
  441. "utf8",
  442. );
  443. // loadError 态下 webview 必须 hidden,避免一个坏掉的 webview 还占着视觉位
  444. expect(source).toMatch(/loadError && "hidden"/);
  445. });
  446. it("keeps the initial webview src stable when the app theme changes while open", () => {
  447. const props = {
  448. credentialService: { load: vi.fn(() => Promise.resolve(null)) },
  449. onOpenChange: vi.fn(),
  450. open: true,
  451. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  452. };
  453. const view = render(createElement(CodingPlanEmbeddedWebviewDialog, props));
  454. const webview = view.getByTestId("coding-plan-embedded-webview");
  455. const initialSrc = webview.getAttribute("src");
  456. expect(initialSrc).toContain("theme=zai-light");
  457. h.theme = "zai-dark";
  458. view.rerender(createElement(CodingPlanEmbeddedWebviewDialog, props));
  459. // 修复原因:支付授权可能持续数分钟,系统主题自动切换不能让 src 变化并重载 PayPal 流程。
  460. expect(view.getByTestId("coding-plan-embedded-webview").getAttribute("src")).toBe(initialSrc);
  461. });
  462. it("wires onPurchaseComplete via ipc-message from the webview preload", () => {
  463. const source = readFileSync(
  464. resolve("packages/ui/src/settings/CodingPlanEmbeddedWebviewDialog.tsx"),
  465. "utf8",
  466. );
  467. // 完成回传协议:官网页通过 window.zcodeBridge.notifyPurchaseComplete
  468. // → preload ipcRenderer.sendToHost(PurchaseComplete 频道)
  469. // → host renderer webview.addEventListener("ipc-message")
  470. // → onPurchaseCompleteRef.current?.() → CodingPlanUpgradeDialog 刷新+关闭
  471. expect(source).toContain("onPurchaseComplete");
  472. expect(source).toContain("onPurchaseCompleteRef");
  473. expect(source).toContain('addEventListener("ipc-message"');
  474. expect(source).toContain("CodingPlanWebviewChannels.PurchaseComplete");
  475. expect(source).toContain("CodingPlanPurchaseCompletePayload");
  476. expect(source).toContain("buildCodingPlanEmbeddedReportContext");
  477. expect(source).toContain("platform.getDeviceId()");
  478. // provider payload 校验:只接受 zai / bigmodel
  479. expect(source).toContain('raw?.provider !== "zai"');
  480. expect(source).toContain('raw?.provider !== "bigmodel"');
  481. });
  482. it("exposes getReportContext on the coding plan webview preload bridge", () => {
  483. const source = readFileSync(
  484. resolve("packages/desktop/src/preload/codingPlanWebview.ts"),
  485. "utf8",
  486. );
  487. expect(source).toContain("getReportContext()");
  488. expect(source).toContain("__zcodeReportContext__");
  489. expect(source).toContain("REPORT_CONTEXT_VAR");
  490. expect(source).toContain("return value as CodingPlanReportContext");
  491. });
  492. it("exposes webview i18n keys in both locales", () => {
  493. const enUs = readFileSync(resolve("packages/ui/src/i18n/locales/en-US.ts"), "utf8");
  494. const zhCn = readFileSync(resolve("packages/ui/src/i18n/locales/zh-CN.ts"), "utf8");
  495. const keys = [
  496. "settings.modelProvider.codingPlan.webview.title",
  497. "settings.modelProvider.codingPlan.webview.authInjectFailed",
  498. "settings.modelProvider.codingPlan.webview.retry",
  499. "settings.modelProvider.codingPlan.webview.loadFailed",
  500. "settings.modelProvider.codingPlan.webview.openWebsite",
  501. ];
  502. for (const key of keys) {
  503. expect(enUs).toContain(`"${key}":`);
  504. expect(zhCn).toContain(`"${key}":`);
  505. }
  506. });
  507. it("keeps refreshCodingPlanUpgradeCompletion exported for the future purchase-complete bridge", () => {
  508. const source = readFileSync(
  509. resolve("packages/ui/src/settings/CodingPlanUpgradeDialog.tsx"),
  510. "utf8",
  511. );
  512. // onPurchaseComplete 触发 closeAndRefreshCodingPlanUpgradeFromWebview:
  513. // 先关闭升级 webview,再刷新 App 侧 provider/权益状态。
  514. expect(source).toContain("export async function refreshCodingPlanUpgradeCompletion");
  515. expect(source).toContain("export async function closeAndRefreshCodingPlanUpgradeFromWebview");
  516. expect(source).toContain("refreshTeamPlanProducts");
  517. expect(source).toContain("codingPlanSubscriptionService.getEnterprisePricing");
  518. expect(source).toContain("const teamPlanFamily");
  519. expect(source).toContain("resolveModelProviderFamilyIdByProviderId(productsProviderId)");
  520. expect(source).toContain("family: teamPlanFamily");
  521. expect(source).toContain("handlePurchaseComplete");
  522. expect(source).toContain("onPurchaseComplete={handlePurchaseComplete}");
  523. expect(source).toContain("onClose,");
  524. expect(source).toContain("refresh: () =>");
  525. expect(source).not.toContain("refreshModelProviderSnapshot");
  526. expect(source).not.toContain("refreshCodingPlanApiKey");
  527. });
  528. it("clears the persistent webview partition on logout and provider unlink boundaries", () => {
  529. const rootActionsSource = readFileSync(
  530. resolve("packages/ui/src/root/useRootWorkspaceActions.ts"),
  531. "utf8",
  532. );
  533. const settingsSource = readFileSync(
  534. resolve("packages/ui/src/settings/ModelProviderSection.tsx"),
  535. "utf8",
  536. );
  537. expect(rootActionsSource).toContain("DesktopCommandIds.ClearCodingPlanWebviewStorage");
  538. expect(rootActionsSource.indexOf("ClearCodingPlanWebviewStorage")).toBeLessThan(
  539. rootActionsSource.indexOf("DesktopCommandIds.RelaunchApp"),
  540. );
  541. expect(settingsSource).toContain("DesktopCommandIds.ClearCodingPlanWebviewStorage");
  542. });
  543. it("keeps manual provider refresh wired to both team plan families", () => {
  544. const settingsSource = readFileSync(
  545. resolve("packages/ui/src/settings/ModelProviderSection.tsx"),
  546. "utf8",
  547. );
  548. expect(settingsSource).toContain("const refreshAuthenticatedEnterpriseProducts = useCallback");
  549. expect(settingsSource).toContain("authenticatedZaiEnterpriseProducts.refresh");
  550. expect(settingsSource).toContain(
  551. "refreshTeamPlanProducts: refreshAuthenticatedEnterpriseProducts",
  552. );
  553. expect(settingsSource).not.toContain(
  554. "refreshTeamPlanProducts: () =>\n authenticatedEnterpriseProducts.refresh({ force: true })",
  555. );
  556. });
  557. });