zcodeAgentService.accountRequestAuth.test.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. zcodeProtocolMethods,
  4. zcodeProtocolNotifications,
  5. requiresRequestVerification,
  6. } from "@zcode/shared";
  7. import type { AccountRequestAuthMaterial } from "../src/model-provider/accountRequestAuthService.js";
  8. import { offPeakSelectionView } from "./fixtures/offPeakSelection.js";
  9. // 账号套餐的 provider runtime headers 由 Host 自动应答,不依赖 Renderer。
  10. const target = {
  11. workspacePath: "/test/account-auth",
  12. sessionId: "sess-account-auth",
  13. requestId: "account-auth-1",
  14. };
  15. async function setup(
  16. resolveCurrent = vi.fn(
  17. async (): Promise<AccountRequestAuthMaterial> => ({
  18. apiKey: "host-key",
  19. apiKeyId: "host-key-id",
  20. headers: { Authorization: "Bearer host-only" },
  21. }),
  22. ),
  23. ) {
  24. let receive: ((request: unknown) => void) | undefined;
  25. let notify: ((message: unknown) => void) | undefined;
  26. const respond = vi.fn(async () => {});
  27. vi.resetModules();
  28. vi.doMock("../src/zcode-agent/zcodeAgentProcessManager.js", () => ({
  29. ZCodeAgentProcessManager: class {
  30. onRuntimeLifecycle() {
  31. return { dispose() {} };
  32. }
  33. onRuntimeRestarted() {
  34. return { dispose() {} };
  35. }
  36. markReady() {}
  37. disposeAll() {}
  38. async getClient() {
  39. return {
  40. request: vi.fn(),
  41. respond,
  42. respondError: vi.fn(),
  43. transportKind: "stdio",
  44. onRequest(listener: typeof receive) {
  45. receive = listener;
  46. return { dispose() {} };
  47. },
  48. onNotification(listener: typeof notify) {
  49. notify = listener;
  50. return { dispose() {} };
  51. },
  52. onClose() {
  53. return { dispose() {} };
  54. },
  55. };
  56. }
  57. },
  58. }));
  59. const { createZCodeAgentService } = await import("../src/zcode-agent/zcodeAgentService.js");
  60. const service = createZCodeAgentService({
  61. modelSelectionReadinessSource: { getView: async () => offPeakSelectionView() },
  62. accountRequestAuthService: {
  63. resolveCurrent,
  64. resolveAccessCurrent: async () => null,
  65. assertCurrent: async () => {},
  66. },
  67. });
  68. await service.initialize(target);
  69. const workspace = { workspacePath: target.workspacePath, workspaceKey: target.workspacePath };
  70. const fire = (
  71. mode: "start-plan" | "individual-coding-plan" | "off-peak" = "start-plan",
  72. expectedAccountScope?: string,
  73. rejectedProjectTokenFingerprint?: string,
  74. ) =>
  75. receive?.({
  76. id: "protocol-1",
  77. method: zcodeProtocolMethods.interactionRequestProviderRuntimeHeaders,
  78. params: {
  79. requestId: target.requestId,
  80. sessionId: target.sessionId,
  81. workspace,
  82. providerId: `account:zai-${mode}`,
  83. modelSelection: { providerId: `account:zai-${mode}`, modelId: "GLM-5.2" },
  84. accountAccess: { type: "zhipu-account", accountType: "zai", mode, entitled: true },
  85. reason: "model-request",
  86. ...(expectedAccountScope ? { expectedAccountScope } : {}),
  87. ...(rejectedProjectTokenFingerprint ? { rejectedProjectTokenFingerprint } : {}),
  88. },
  89. });
  90. const cancel = () =>
  91. notify?.({
  92. method: zcodeProtocolNotifications.providerRuntimeHeadersCancelled,
  93. params: { requestId: target.requestId, sessionId: target.sessionId, workspace },
  94. });
  95. return { service, fire, cancel, respond, resolveCurrent };
  96. }
  97. describe("Host 自动应答账号请求鉴权", () => {
  98. it("individual-coding-plan:凭据解析期间取消,不回传迟到材料", async () => {
  99. const deferred = Promise.withResolvers<AccountRequestAuthMaterial>();
  100. const { service, fire, cancel, respond } = await setup(vi.fn(() => deferred.promise));
  101. try {
  102. fire("individual-coding-plan");
  103. cancel();
  104. deferred.resolve({ apiKey: "late-key" });
  105. await new Promise<void>((resolve) => setImmediate(resolve));
  106. expect(respond).not.toHaveBeenCalled();
  107. } finally {
  108. service.disposeAll();
  109. }
  110. });
  111. it("闲时 scope 在 Host 私有 owner 校验,无需 Renderer 应答", async () => {
  112. const accountScope = "a".repeat(64);
  113. const resolve = vi.fn(async () => ({ apiKey: "fresh-pat", accountScope }));
  114. const { service, fire, respond } = await setup(resolve);
  115. try {
  116. fire("off-peak", accountScope, "b".repeat(64));
  117. await vi.waitFor(() =>
  118. expect(respond).toHaveBeenCalledWith("protocol-1", {
  119. headersApplied: true,
  120. requestAuth: { apiKey: "fresh-pat", accountScope },
  121. }),
  122. );
  123. expect(resolve).toHaveBeenCalledWith(
  124. expect.objectContaining({
  125. expectedAccountScope: accountScope,
  126. rejectedProjectTokenFingerprint: "b".repeat(64),
  127. accountAccess: expect.objectContaining({ mode: "off-peak" }),
  128. }),
  129. );
  130. } finally {
  131. service.disposeAll();
  132. }
  133. });
  134. });
  135. it("edition policy selects interaction without changing the Host credential owner", async () => {
  136. const { service, fire, respond, resolveCurrent } = await setup();
  137. const listener = vi.fn();
  138. const subscription = service.onDynamicWorkspaceProviderRuntimeHeadersRequest({
  139. workspacePath: target.workspacePath,
  140. })(listener);
  141. try {
  142. fire("start-plan");
  143. if (requiresRequestVerification({ mode: "start-plan" })) {
  144. expect(listener).toHaveBeenCalledOnce();
  145. expect(resolveCurrent).not.toHaveBeenCalled();
  146. await service.respondProviderRuntimeHeaders({
  147. ...target,
  148. response: { headersApplied: true, runtimeProviderHeaders: {} },
  149. });
  150. } else {
  151. expect(listener).not.toHaveBeenCalled();
  152. }
  153. await vi.waitFor(() =>
  154. expect(respond).toHaveBeenCalledExactlyOnceWith("protocol-1", {
  155. headersApplied: true,
  156. requestAuth: {
  157. apiKey: "host-key",
  158. apiKeyId: "host-key-id",
  159. headers: { Authorization: "Bearer host-only" },
  160. },
  161. }),
  162. );
  163. expect(resolveCurrent).toHaveBeenCalledOnce();
  164. } finally {
  165. subscription.dispose();
  166. service.disposeAll();
  167. }
  168. });