provider-key-native-open.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { ApiKeyAccessConfig, ProviderConfig } from "@zcode/provider";
  2. import { NodePersonalProviderConfigRepository } from "@zcode/provider-node";
  3. import { createServer } from "node:http";
  4. import { readFile } from "node:fs/promises";
  5. import { randomUUID } from "node:crypto";
  6. import {
  7. TID_MODEL_PROVIDER_NAV_ITEM,
  8. TID_SETTINGS_SECTION_NAV,
  9. TID_TASK_SETTINGS_BUTTON,
  10. testId,
  11. } from "@zcode/shared/test-ids";
  12. import { clearAppData, clickTestIdByDom, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  13. import { restartIntoWorkspace, seedReplayProvider } from "#e2e/helpers/model-provider-restart";
  14. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  15. describe("Todo116 单一 Key 链接原生打开", () => {
  16. after(async () => {
  17. await browser.electron.restoreAllMocks();
  18. await clearAppData();
  19. });
  20. it("K116-N01:两类手动 Access 从唯一入口打开配置 URL,不修改配置", async function () {
  21. this.timeout(120_000);
  22. const received = new Set<string>();
  23. const nonce = randomUUID();
  24. const variants = [
  25. {
  26. id: "e2e-key-native-standard",
  27. type: "api-key",
  28. apiKey: "e2e-only",
  29. templateId: "zai-standard-api",
  30. },
  31. {
  32. id: "e2e-key-native-plan",
  33. type: "zhipu-coding-plan-api-key",
  34. apiKey: "",
  35. templateId: "zai-api",
  36. },
  37. ] as const;
  38. const targets = new Set(variants.map(({ id }) => `/E2E_KEY_NATIVE/${nonce}/${id}`));
  39. // 只记录本例 canary 路径,不收集默认浏览器的 Cookie、历史或其他页面。
  40. const server = createServer((request, response) => {
  41. if (request.method === "GET" && targets.has(request.url ?? "")) {
  42. received.add(request.url!);
  43. response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
  44. response.end(
  45. "<title>ZCode E2E</title><p>API Key link verification passed. You may close this test tab.</p>",
  46. );
  47. } else {
  48. response.writeHead(404);
  49. response.end();
  50. }
  51. });
  52. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  53. const address = server.address();
  54. if (!address || typeof address === "string") throw new Error("Missing canary port");
  55. const repository = new NodePersonalProviderConfigRepository({
  56. filePath: getE2EAppDataPaths().configFile,
  57. pollingIntervalMs: false,
  58. });
  59. try {
  60. await prepareV4ConversationE2E({ skipProvider: true });
  61. await restartIntoWorkspace({
  62. afterElectronProcessExit: async () => {
  63. for (const variant of variants) {
  64. await seedReplayProvider({
  65. id: variant.id,
  66. name: variant.id,
  67. apiKey: variant.apiKey,
  68. models: ["E2E_KEY_NATIVE_MODEL"],
  69. });
  70. await repository.update((current) => {
  71. const rule = current.providers.getRule(variant.id)!;
  72. return {
  73. ...current,
  74. providers: current.providers.setRule({
  75. ...rule,
  76. // 入口仅供预设模板实例;纯自定义 Provider 不应被测试擅自要求显示链接。
  77. templateId: variant.templateId,
  78. config: rule.config.overlay(
  79. new ProviderConfig({
  80. access: new ApiKeyAccessConfig({
  81. type: variant.type,
  82. apiKey: variant.apiKey,
  83. apiKeyManagementUrl: `http://127.0.0.1:${address.port}/E2E_KEY_NATIVE/${nonce}/${variant.id}`,
  84. }),
  85. }),
  86. ),
  87. }),
  88. };
  89. });
  90. }
  91. },
  92. });
  93. const before = await readFile(getE2EAppDataPaths().configFile, "utf8");
  94. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  95. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "modelProvider"));
  96. for (const { id } of variants) {
  97. await clickTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, `custom:${id}`));
  98. const selector =
  99. '//button[normalize-space(.)="获取 API Key" or normalize-space(.)="Get API Key"]';
  100. await $(selector).waitForClickable({ timeout: 15_000 });
  101. const links = await $$(selector);
  102. expect(links).toHaveLength(1);
  103. const path = `/E2E_KEY_NATIVE/${nonce}/${id}`;
  104. expect(received.has(path)).toBe(false);
  105. // 不 mock shell:必须走真实按钮、preload、main IPC,最终由系统浏览器访问 canary。
  106. await links[0]!.click();
  107. await browser.waitUntil(() => received.has(path), {
  108. timeout: 15_000,
  109. timeoutMsg: `${id} 未通过系统默认浏览器打开精确配置 URL`,
  110. });
  111. // canary 不能只是 Electron 内部导航;主设置页仍在,所有内嵌页面均未打开目标。
  112. expect(
  113. await browser.electron.execute(
  114. (electron, target) =>
  115. electron.webContents
  116. .getAllWebContents()
  117. .some((contents) => contents.getURL() === target),
  118. `http://127.0.0.1:${address.port}${path}`,
  119. ),
  120. ).toBe(false);
  121. await $(selector).waitForDisplayed({ timeout: 15_000 });
  122. }
  123. expect(await readFile(getE2EAppDataPaths().configFile, "utf8")).toBe(before);
  124. } finally {
  125. repository.dispose();
  126. server.closeAllConnections();
  127. await new Promise<void>((resolve, reject) =>
  128. server.close((error) => (error ? reject(error) : resolve())),
  129. );
  130. }
  131. });
  132. });