rootOAuthCallbackCancellation.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { describe, expect, it, vi } from "vitest";
  2. const { effects, errorLog } = vi.hoisted(() => ({
  3. effects: [] as Array<() => unknown>,
  4. errorLog: vi.fn(),
  5. }));
  6. vi.mock("react", async (original) => ({
  7. ...(await original<typeof import("react")>()),
  8. useEffect: (effect: () => unknown) => effects.push(effect),
  9. useRef: (current: unknown) => ({ current }),
  10. }));
  11. vi.mock("@/hooks/useAlertDialog.js", () => ({ useAlertDialog: () => vi.fn() }));
  12. vi.mock("@/i18n/IntlProvider.js", () => ({
  13. useZCodeIntl: () => ({ intl: { formatMessage: () => "登录失败" } }),
  14. }));
  15. vi.mock("@/root/useAccountConnectionLossNotification.js", () => ({
  16. useAccountConnectionLossNotification: vi.fn(),
  17. }));
  18. vi.mock("@/logger.js", () => ({
  19. logger: { info: vi.fn(), warn: vi.fn(), error: errorLog },
  20. }));
  21. import { useRootOAuthEffects } from "@/root/useRootOAuthEffects.js";
  22. describe("失效 OAuth 回调", () => {
  23. it.each([true, false])("pollingActive=%s 时静默忽略取消结果", async (oauthPollingActive) => {
  24. effects.length = 0;
  25. errorLog.mockClear();
  26. let callback!: (url: string) => Promise<void>;
  27. const setUser = vi.fn();
  28. const setOAuthError = vi.fn();
  29. const markOAuthSuccess = vi.fn();
  30. const setOAuthPollingActive = vi.fn();
  31. useRootOAuthEffects({
  32. accountIntentKey: "test",
  33. platform: {
  34. notifyRendererReady: vi.fn(),
  35. onOAuthCallback: (handler: typeof callback) => {
  36. callback = handler;
  37. return vi.fn();
  38. },
  39. } as never,
  40. services: {
  41. oauthService: { handleCallback: vi.fn(async () => null) },
  42. broadcastService: {},
  43. } as never,
  44. refreshProviderState: vi.fn(async () => {}),
  45. setUser,
  46. setIsRestoringOAuthSession: vi.fn(),
  47. setOAuthError,
  48. oauthPollingActive,
  49. setOAuthPollingActive,
  50. markOAuthSuccess,
  51. onReauthenticationRequired: vi.fn(),
  52. });
  53. // 只挂载回调订阅;启动恢复和轮询在各自测试中验证。
  54. effects.at(-1)!();
  55. await callback("zcode://oauth/callback?state=cancelled");
  56. expect(errorLog).not.toHaveBeenCalled();
  57. expect(setUser).not.toHaveBeenCalled();
  58. expect(setOAuthError).not.toHaveBeenCalled();
  59. expect(markOAuthSuccess).not.toHaveBeenCalled();
  60. expect(setOAuthPollingActive).not.toHaveBeenCalled();
  61. });
  62. });
  63. describe("OAuth 成功后的真实设置 CAS", () => {
  64. it.each(["polling", "deep-link"] as const)("%s 保留并发连接并完成成功收尾", async (mode) => {
  65. const { mkdtemp, rm } = await import("node:fs/promises");
  66. const { tmpdir } = await import("node:os");
  67. const { join } = await import("node:path");
  68. const { createSettingService } = await import("@zcode/services/node");
  69. const root = await mkdtemp(join(tmpdir(), "oauth-cas-"));
  70. const previousHome = process.env.ZCODE_DESKTOP_HOME_DIR;
  71. process.env.ZCODE_DESKTOP_HOME_DIR = root;
  72. const setting = createSettingService();
  73. if (previousHome === undefined) delete process.env.ZCODE_DESKTOP_HOME_DIR;
  74. else process.env.ZCODE_DESKTOP_HOME_DIR = previousHome;
  75. effects.length = 0;
  76. let poll!: () => void;
  77. let callback!: (url: string) => Promise<void>;
  78. const previousWindow = globalThis.window;
  79. vi.stubGlobal("window", {
  80. setInterval: (fn: () => void) => {
  81. poll = fn;
  82. return 1;
  83. },
  84. clearInterval: vi.fn(),
  85. });
  86. let injected = false;
  87. let concurrentVersion = 0;
  88. const newer = {
  89. kind: "team-coding-plan" as const,
  90. productId: "p",
  91. organizationId: "o",
  92. projectId: "j",
  93. };
  94. const result = {
  95. kind: "session",
  96. provider: "bigmodel",
  97. userInfo: { id: "user", username: "user" },
  98. };
  99. const setUser = vi.fn();
  100. const setOAuthError = vi.fn();
  101. const markOAuthSuccess = vi.fn();
  102. const providerRefresh = vi.fn(async () => ({
  103. providers: [
  104. {
  105. providerId: "account:bigmodel-individual-coding-plan",
  106. accountState: { availability: "available", entitled: true, current: false },
  107. },
  108. ],
  109. }));
  110. const refreshProviderState = vi.fn(async () => {
  111. await providerRefresh();
  112. });
  113. const refreshAppSettings = vi.fn(async () => {
  114. await setting.get();
  115. });
  116. const admission = vi.fn();
  117. try {
  118. useRootOAuthEffects({
  119. accountIntentKey: "test",
  120. oauthPollingActive: mode === "polling",
  121. platform: {
  122. notifyRendererReady: vi.fn(),
  123. reportTelemetryEvent: vi.fn(async () => {}),
  124. onOAuthCallback: (fn: typeof callback) => {
  125. callback = fn;
  126. return vi.fn();
  127. },
  128. } as never,
  129. services: {
  130. oauthService: {
  131. pollPendingOAuth: async () => result,
  132. handleCallback: async () => result,
  133. },
  134. settingService: {
  135. get: () => setting.get(),
  136. update: async (patch: any, expected: any) => {
  137. admission(patch);
  138. if (!injected) {
  139. injected = true;
  140. const current = await setting.get();
  141. await setting.update(
  142. {
  143. providerFamilyConnectionSelections: {
  144. ...current.providerFamilyConnectionSelections,
  145. bigmodel: newer,
  146. },
  147. },
  148. {
  149. providerFamilyDomain: current.providerFamilyDomain,
  150. providerFamilyConnectionSelections: current.providerFamilyConnectionSelections,
  151. providerFamilyDomainUpdatedAt: current.providerFamilyDomainUpdatedAt ?? 0,
  152. },
  153. );
  154. concurrentVersion = (await setting.get()).providerFamilyDomainUpdatedAt ?? 0;
  155. }
  156. return setting.update(patch, expected);
  157. },
  158. },
  159. providerSettingsService: { refresh: providerRefresh },
  160. usageStatsService: { getEntitlementSnapshot: async () => null },
  161. codingPlanSubscriptionService: {
  162. getEnterprisePricing: async () => ({ productList: [] }),
  163. },
  164. broadcastService: {},
  165. } as never,
  166. refreshProviderState,
  167. refreshAppSettings,
  168. setUser,
  169. setOAuthError,
  170. markOAuthSuccess,
  171. setIsRestoringOAuthSession: vi.fn(),
  172. setOAuthPollingActive: vi.fn(),
  173. onReauthenticationRequired: vi.fn(),
  174. });
  175. if (mode === "polling") {
  176. effects.at(-2)!();
  177. poll();
  178. } else {
  179. effects.at(-1)!();
  180. await callback("zcode://oauth/callback?state=test");
  181. }
  182. await vi.waitFor(() => expect(markOAuthSuccess).toHaveBeenCalledWith("bigmodel"));
  183. expect(setUser).toHaveBeenCalledWith(result.userInfo);
  184. expect(setOAuthError).toHaveBeenCalledExactlyOnceWith(null);
  185. expect(refreshProviderState).toHaveBeenCalledOnce();
  186. expect((await setting.get()).providerFamilyConnectionSelections?.bigmodel).toEqual(newer);
  187. expect((await setting.get()).providerFamilyDomainUpdatedAt).toBe(concurrentVersion);
  188. expect(admission).toHaveBeenCalledOnce();
  189. expect(providerRefresh).toHaveBeenCalledOnce();
  190. expect(refreshAppSettings).toHaveBeenCalledOnce();
  191. } finally {
  192. vi.stubGlobal("window", previousWindow);
  193. await rm(root, { recursive: true, force: true });
  194. }
  195. });
  196. });