worker-selection-integration.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import type { ProjectRepositoryContract } from "../../../../services/src/project-storage/contract.js";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { join, resolve } from "node:path";
  4. import {
  5. MutableAccountProviderConfigSource,
  6. ProviderConfig,
  7. ProviderConfigMap,
  8. ZhipuAccountAccessConfig,
  9. createAccountProviderConfigSnapshot,
  10. createFailClosedAccountProviderConfigSnapshot,
  11. type ModelSelectionViewInput,
  12. } from "@zcode/provider";
  13. import { NodeProviderRegistryRuntime, createNodeModelSelectionFacade } from "@zcode/provider-node";
  14. import {
  15. createZCodeAgentService,
  16. createZCodeTaskServiceAdapter,
  17. getDataBaseDir,
  18. setDataBaseDir,
  19. } from "@zcode/services/node";
  20. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  21. import { TaskIndexRepo } from "../../../../services/src/session/taskIndexRepo.js";
  22. import { createZCodeTaskIndexSyncer } from "../../../../services/src/zcode-agent/zcodeTaskIndexSyncer.js";
  23. import { getE2EAppDataPaths } from "./desktop-app.js";
  24. /** 独立测试 Host + 真实 stdio Worker;仅账号上游和模型 HTTP 使用隔离 fixture。 */
  25. export async function createWorkerSelectionIntegration(
  26. directory = "worker-selection-host",
  27. options: { workspacePath?: string; cliNodeArgs?: string[] } = {},
  28. ) {
  29. const paths = getE2EAppDataPaths();
  30. const home = join(paths.homeDir, directory);
  31. const workspacePath = options.workspacePath ?? join(home, "workspace");
  32. await mkdir(workspacePath, { recursive: true });
  33. const previousDataDir = getDataBaseDir();
  34. setDataBaseDir(home);
  35. const source = new MutableAccountProviderConfigSource();
  36. const deliverySource = new MutableAccountProviderConfigSource();
  37. let deliveryPaused = false;
  38. const runtimePaths = {
  39. zcodeBuiltinFilePath: resolve("../../config/provider/zcode-builtin.json"),
  40. personalFilePath: join(home, ".zcode/v2/provider_config.json"),
  41. };
  42. // 独立 Host 不继承 Electron 设置。保持内建 HTTPS endpoint,
  43. // 将显式网络出口接到本轮数据面代理,避免假凭据直连或 HTTP 被官方请求安全校验拒绝。
  44. const httpProxy = process.env.ZCODE_HTTP_PROXY?.trim();
  45. const caCertFile = process.env.ZCODE_AGENT_CA_CERT?.trim();
  46. if (!httpProxy || !caCertFile) throw new Error("Worker 选择回归缺少隔离 HTTPS 数据面代理");
  47. await mkdir(join(home, ".zcode/cli"), { recursive: true });
  48. await writeFile(
  49. join(home, ".zcode/cli/config.json"),
  50. JSON.stringify({
  51. network: { httpProxy, caCertFile, noProxy: process.env.ZCODE_NO_PROXY },
  52. }),
  53. );
  54. const runtime = new NodeProviderRegistryRuntime({
  55. ...runtimePaths,
  56. accountSource: source,
  57. watch: false,
  58. personalPollingIntervalMs: false,
  59. });
  60. await runtime.start();
  61. const config = await runtime.configService.read();
  62. const individual = BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan;
  63. const team = BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan;
  64. const modelId = "GLM-5.3-Flash";
  65. async function selectAccount(providerId: string) {
  66. const base = createFailClosedAccountProviderConfigSnapshot(config);
  67. const providers = new Map(base.providers.entries());
  68. for (const id of [individual, team]) {
  69. providers.set(
  70. id,
  71. new ProviderConfig({
  72. access: new ZhipuAccountAccessConfig({ entitled: true }),
  73. builtinModelIds: [modelId],
  74. }),
  75. );
  76. }
  77. source.replace(
  78. createAccountProviderConfigSnapshot(
  79. config.zcodeBuiltinRevision,
  80. new ProviderConfigMap([...providers]),
  81. Object.fromEntries(
  82. [individual, team].map((id) => [
  83. id,
  84. {
  85. availability: "available" as const,
  86. entitled: true,
  87. current: id === providerId,
  88. },
  89. ]),
  90. ),
  91. ),
  92. );
  93. await runtime.registryService.refresh("test-account-change");
  94. if (!deliveryPaused) deliverySource.replace(await source.read());
  95. }
  96. await selectAccount(individual);
  97. const facade = createNodeModelSelectionFacade(runtime.registryService);
  98. const modelSelectionService = {
  99. getView: async (input?: ModelSelectionViewInput) => facade.getView(undefined, undefined, input),
  100. onDidChange: (listener: Parameters<typeof facade.onDidChange>[0]) => ({
  101. dispose: facade.onDidChange(listener),
  102. }),
  103. };
  104. const repo = new TaskIndexRepo();
  105. const projects: ProjectRepositoryContract = await repo.getProjectRepository();
  106. const agent = createZCodeAgentService({
  107. // 真实 Host 创建端口必须预留任务归属;旧夹具漏装配,Worker 启动前即报 creation-unavailable。
  108. prepareSessionCreation: async (target) => {
  109. const prepared = projects.reserveCreatedTask({
  110. task: { ...target, taskId: target.sessionId },
  111. projectId: target.projectId,
  112. creationCommand: target.creationCommand,
  113. additionalDirectories: target.additionalDirectories,
  114. });
  115. return { sessionId: prepared.taskId, additionalDirectories: prepared.additionalDirectories };
  116. },
  117. commandResolver: () => ({
  118. command: process.execPath,
  119. args: [
  120. ...(options.cliNodeArgs ?? []),
  121. resolve("../../apps/zcode-cli/packages/cli/dist/zcode.cjs"),
  122. "app-server",
  123. "--stdio",
  124. ],
  125. env: {
  126. HOME: home,
  127. USERPROFILE: home,
  128. ZCODE_DATA_BASE_DIR: home,
  129. ZCODE_RUNTIME_ENV: "development",
  130. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: runtimePaths.zcodeBuiltinFilePath,
  131. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE: runtimePaths.personalFilePath,
  132. },
  133. }),
  134. modelSelectionReadinessSource: modelSelectionService,
  135. accountProviderConfigSource: deliverySource,
  136. // 测试只核对选择合同;不使用真实账号、真实 secret 或外部 IM 网络。
  137. accountRequestAuthService: {
  138. resolveAccessCurrent: async () => ({
  139. type: "zhipu-account",
  140. family: "bigmodel",
  141. planKind: "team-coding-plan",
  142. productId: "product-team-a",
  143. organizationId: "org-team-a",
  144. projectId: "proj-team-a",
  145. }),
  146. // 合成凭据仍须符合账号接口的 key.secret 形状;裸标签会在本地校验阶段被拒绝。
  147. resolveCurrent: async () => ({ apiKey: "e2e-fixture-key.synthetic-secret" }),
  148. assertCurrent: async () => {},
  149. },
  150. // 夹具只用 Team Plan,不会读取验证配置;返回 null 保持 Start Plan 失败关闭的正式语义。
  151. readRequestVerificationConfig: async () => null,
  152. });
  153. const syncer = createZCodeTaskIndexSyncer({ agentService: agent, taskIndexRepo: repo });
  154. const task = createZCodeTaskServiceAdapter({
  155. zcodeAgentService: agent,
  156. taskIndexRepo: repo,
  157. taskIndexSyncer: syncer,
  158. });
  159. return {
  160. home,
  161. repo,
  162. projects,
  163. workspacePath,
  164. agent,
  165. task,
  166. modelSelectionService,
  167. selectAccount,
  168. async setDeliveryPaused(paused: boolean) {
  169. deliveryPaused = paused;
  170. if (!paused) deliverySource.replace(await source.read());
  171. },
  172. async dispose() {
  173. syncer.disposeAll();
  174. await agent.disposeWorkspace({ workspacePath });
  175. await agent.disposeAllAndWait();
  176. repo.close();
  177. runtime.dispose();
  178. setDataBaseDir(previousDataDir);
  179. },
  180. };
  181. }