project-location-decrypt-recovery.test.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  3. import { TID_LOGIN_TRIGGER, TID_TASK_SETTINGS_BUTTON } from "@zcode/shared/test-ids";
  4. import { clearAppData, clickTestIdByDom, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  5. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  6. import { skipOccupationOnboardingIfPresent } from "#e2e/helpers/occupation-onboarding";
  7. interface Status {
  8. locationRequests: number;
  9. tokenRequests: number;
  10. loginCompletions: number;
  11. }
  12. const readCredentials = async () =>
  13. JSON.parse(await readFile(getE2EAppDataPaths().credentialsFile, "utf8")) as Record<
  14. string,
  15. string
  16. >;
  17. async function assertLoggedIn(before: Record<string, string>) {
  18. await skipOccupationOnboardingIfPresent();
  19. await browser.waitUntil(
  20. async () => {
  21. const label = await browser
  22. .$(`[data-testid="${TID_LOGIN_TRIGGER}"]`)
  23. .getAttribute("aria-label");
  24. return label?.includes("Fixture User") === true;
  25. },
  26. { timeout: 30000, timeoutMsg: "有效登录头像没有保留" },
  27. );
  28. const after = await readCredentials();
  29. for (const [key, value] of Object.entries(before)) {
  30. if (key.startsWith("oauth:") || key === "zcodejwttoken" || key === "bot:e2e:credential")
  31. expect(after[key]).toBe(value);
  32. }
  33. const expired = await browser.execute(() =>
  34. /登录已过期|Your session has expired/u.test(
  35. document.querySelector('[data-slot="alert-dialog-title"]')?.textContent ?? "",
  36. ),
  37. );
  38. expect(expired).toBe(false);
  39. }
  40. describe("项目位置缓存局部恢复", () => {
  41. after(async () => {
  42. await browser.electron.restoreAllMocks();
  43. await clearAppData();
  44. });
  45. it("自动重建坏位置;503 保留登录;服务恢复后通过设置刷新成功", async function () {
  46. this.timeout(180_000);
  47. const baseUrl = process.env.ZCODE_E2E_ACCESS_TOKEN_401_URL;
  48. if (!baseUrl) throw new Error("缺少项目位置恢复 fixture");
  49. const status = async () => (await (await fetch(`${baseUrl}/__e2e/status`)).json()) as Status;
  50. const before = await readCredentials();
  51. await browser.waitUntil(async () => (await status()).tokenRequests > 0, {
  52. timeout: 30000,
  53. timeoutMsg: "坏缓存没有自动重建并签发 Token",
  54. });
  55. await assertLoggedIn(before);
  56. const healthy = await readCredentials();
  57. const locationKey = Object.keys(healthy).find((key) =>
  58. key.startsWith("project-key-location:v1:"),
  59. );
  60. expect(locationKey).toBeDefined();
  61. expect(healthy[locationKey!]).toMatch(/^enc:v1:/);
  62. expect(healthy[locationKey!]).not.toBe("enc:v1:broken-project-location");
  63. expect((await status()).loginCompletions).toBe(0);
  64. // 故障夹具只在旧进程完全退出后改写,避免与产品持久化发生测试自身的竞态。
  65. const previousRequests = (await status()).locationRequests;
  66. await fetch(`${baseUrl}/__e2e/location-unavailable`);
  67. await reloadElectronSessionPreservingBrowserProfile(browser, {
  68. afterElectronProcessExit: async () => {
  69. const raw = await readCredentials();
  70. raw[locationKey!] = "enc:v1:broken-project-location";
  71. await writeFile(getE2EAppDataPaths().credentialsFile, JSON.stringify(raw));
  72. },
  73. });
  74. await browser.waitUntil(async () => (await status()).locationRequests > previousRequests, {
  75. timeout: 30000,
  76. timeoutMsg: "未覆盖到位置重建 503 路径",
  77. });
  78. await assertLoggedIn(healthy);
  79. const relaunch = await browser.electron.mock("app", "relaunch");
  80. await relaunch.mockResolvedValue(undefined);
  81. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  82. await clickTestIdByDom("settings-section-nav-modelProvider");
  83. const previousTokens = (await status()).tokenRequests;
  84. await fetch(`${baseUrl}/__e2e/location-available`);
  85. await browser.waitUntil(
  86. async () =>
  87. browser.execute(() => {
  88. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  89. (el) => !el.disabled && /刷新|refresh/iu.test(el.getAttribute("aria-label") ?? ""),
  90. );
  91. if (!button) return false;
  92. button.click();
  93. return true;
  94. }),
  95. { timeout: 30000, timeoutMsg: "模型供应商设置没有可操作的刷新按钮" },
  96. );
  97. await browser.waitUntil(async () => (await status()).tokenRequests > previousTokens, {
  98. timeout: 30000,
  99. timeoutMsg: "服务恢复后正常刷新没有完成换证",
  100. });
  101. await assertLoggedIn(healthy);
  102. expect((await status()).loginCompletions).toBe(0);
  103. await relaunch.update();
  104. expect(relaunch.mock.calls).toHaveLength(0);
  105. await clickTestIdByDom(
  106. `model-provider-nav-item-preset:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  107. );
  108. await browser.waitUntil(
  109. async () =>
  110. browser.execute(
  111. () =>
  112. document.body.innerText.includes("CODING PRO") &&
  113. Array.from(document.querySelectorAll("button")).some((el) =>
  114. /Unlink|断开|解除|解绑/u.test(el.textContent?.trim() ?? ""),
  115. ),
  116. ),
  117. { timeout: 30000, timeoutMsg: "恢复后没有显示已连接套餐及解绑入口" },
  118. );
  119. console.info("PROJECT_LOCATION_RECOVERY", {
  120. ...(await status()),
  121. oauthPreserved: true,
  122. networkFailurePreservedLogin: true,
  123. });
  124. await browser.saveScreenshot(
  125. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/project-location-recovered.png`,
  126. );
  127. });
  128. });