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

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