offPeakRuntimeModel.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. BUILTIN_MODEL_PROVIDER_IDS,
  4. type AppSettings,
  5. type ZCodeAccountAccess,
  6. } from "@zcode/shared";
  7. import {
  8. OffPeakCodingPlanUnavailableError,
  9. OffPeakCredentialsUnavailableError,
  10. OffPeakModelUnavailableError,
  11. OffPeakPermanentDispatchError,
  12. buildOffPeakRequestAuth,
  13. resolveOffPeakCodingPlanSupport,
  14. resolveOffPeakCredentials,
  15. } from "../src/session/offPeakRuntimeModel.js";
  16. describe("buildOffPeakRequestAuth", () => {
  17. it("只生成逐请求鉴权材料,不携带 Provider 或 Model 静态事实", () => {
  18. const requestAuth = buildOffPeakRequestAuth({
  19. credentials: {
  20. jwt: "zcode-jwt",
  21. codingPlanApiKey: "coding-plan-key",
  22. kind: "bigmodel-personal",
  23. providerFamily: "bigmodel",
  24. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  25. },
  26. ticketId: "ticket-1",
  27. });
  28. expect(requestAuth).toEqual({
  29. apiKey: "zcode-jwt",
  30. headers: {
  31. Authorization: "Bearer zcode-jwt",
  32. "X-Coding-Plan-Api-Key": "coding-plan-key",
  33. "X-Off-Peak-Ticket-ID": "ticket-1",
  34. },
  35. });
  36. expect(requestAuth).not.toHaveProperty("baseURL");
  37. expect(requestAuth).not.toHaveProperty("model");
  38. expect(requestAuth).not.toHaveProperty("reasoning");
  39. expect(requestAuth).not.toHaveProperty("properties");
  40. });
  41. });
  42. describe("OffPeak permanent dispatch errors", () => {
  43. it("只用类型表达确定性模型/凭证配置错误", () => {
  44. expect(new OffPeakModelUnavailableError("workspaceUser")).toBeInstanceOf(
  45. OffPeakPermanentDispatchError,
  46. );
  47. expect(new OffPeakCredentialsUnavailableError("jwt")).toBeInstanceOf(
  48. OffPeakPermanentDispatchError,
  49. );
  50. expect(new Error("network unavailable")).not.toBeInstanceOf(OffPeakPermanentDispatchError);
  51. });
  52. });
  53. type CredentialSettings = Pick<
  54. AppSettings,
  55. "providerFamilyConnectionSelections" | "providerFamilyDomain"
  56. >;
  57. function accountProvider(
  58. providerId: string,
  59. access: ZCodeAccountAccess,
  60. apiKey: string,
  61. baseURL = "https://coding.example.test",
  62. ): AccountProviderFixture {
  63. return {
  64. providerId,
  65. access,
  66. apiKey,
  67. baseURL,
  68. };
  69. }
  70. interface AccountProviderFixture {
  71. readonly providerId: string;
  72. readonly access: ZCodeAccountAccess;
  73. readonly apiKey: string;
  74. readonly baseURL?: string;
  75. }
  76. function individualAccess(family: "zai" | "bigmodel"): ZCodeAccountAccess {
  77. return {
  78. type: "zhipu-account",
  79. family,
  80. planKind: "individual-coding-plan",
  81. };
  82. }
  83. function credentialDeps(params: {
  84. settings: CredentialSettings | CredentialSettings[];
  85. accountProviders: AccountProviderFixture | null | Array<AccountProviderFixture | null>;
  86. activeProvider?: string | null;
  87. jwt?: string | null;
  88. accountScope?: string;
  89. }) {
  90. const providerSequence = Array.isArray(params.accountProviders)
  91. ? [...params.accountProviders]
  92. : null;
  93. const fallbackProvider = Array.isArray(params.accountProviders)
  94. ? (params.accountProviders.at(-1) ?? null)
  95. : params.accountProviders;
  96. let currentProvider = fallbackProvider;
  97. return {
  98. credentialService: {
  99. load: async (key: string) =>
  100. key === "oauth:active_provider"
  101. ? params.activeProvider === undefined
  102. ? (currentProvider?.access.family ?? null)
  103. : params.activeProvider
  104. : params.jwt === undefined
  105. ? "zcode-jwt"
  106. : params.jwt,
  107. },
  108. resolveAccountProvider: async () => {
  109. currentProvider = providerSequence?.shift() ?? fallbackProvider;
  110. return currentProvider
  111. ? {
  112. providerId: currentProvider.providerId,
  113. access: currentProvider.access,
  114. ...(currentProvider.baseURL ? { baseURL: currentProvider.baseURL } : {}),
  115. }
  116. : null;
  117. },
  118. accountRequestAuthService: {
  119. resolveCurrent: async () =>
  120. currentProvider
  121. ? { apiKey: currentProvider.apiKey, accountScope: params.accountScope }
  122. : {},
  123. },
  124. env: {} as NodeJS.ProcessEnv,
  125. };
  126. }
  127. describe("resolveOffPeakCredentials selected Coding Plan matrix", () => {
  128. it("派发时将 owner 的账号作用域传到私有 requestAuth,供后续请求刷新校验", async () => {
  129. const accountScope = "a".repeat(64);
  130. const credentials = await resolveOffPeakCredentials(
  131. credentialDeps({
  132. settings: {},
  133. accountScope,
  134. accountProviders: accountProvider(
  135. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  136. individualAccess("bigmodel"),
  137. "initial-pat",
  138. ),
  139. }),
  140. );
  141. const auth = buildOffPeakRequestAuth({ credentials, ticketId: "ticket-1" });
  142. expect(auth.accountScope).toBe(accountScope);
  143. expect(auth.headers["X-Off-Peak-Ticket-ID"]).toBe("ticket-1");
  144. expect(auth.headers).not.toHaveProperty("accountScope");
  145. });
  146. it.each([
  147. {
  148. name: "ZAI personal",
  149. family: "zai" as const,
  150. selection: { kind: "individual-coding-plan" } as const,
  151. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  152. apiKey: "zai-coding-key",
  153. kind: "zai-personal" as const,
  154. },
  155. {
  156. // 修复原因:zai/bigmodel Team Plan 对称化。原 offPeakRuntimeModel 对 zai team key
  157. // 直接 throw connection_unavailable,zai 团队用户无法走后台任务。锁定 zai-team 正常解析。
  158. name: "ZAI Team",
  159. family: "zai" as const,
  160. selection: {
  161. kind: "team-coding-plan",
  162. productId: "team-pro",
  163. organizationId: "org-zai",
  164. projectId: "project-zai",
  165. } as const,
  166. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan,
  167. apiKey: "zai-team-api-key.zai-team-secret",
  168. kind: "zai-team" as const,
  169. },
  170. {
  171. name: "BigModel personal",
  172. family: "bigmodel" as const,
  173. selection: { kind: "individual-coding-plan" } as const,
  174. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  175. apiKey: "bigmodel-personal-key",
  176. kind: "bigmodel-personal" as const,
  177. },
  178. {
  179. name: "BigModel Team",
  180. family: "bigmodel" as const,
  181. selection: {
  182. kind: "team-coding-plan",
  183. productId: "team-pro",
  184. organizationId: "org-1",
  185. projectId: "project-1",
  186. } as const,
  187. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  188. apiKey: "team-api-key.team-secret-key",
  189. kind: "bigmodel-team" as const,
  190. },
  191. ])("$name resolves the exact selected runtime credential", async (scenario) => {
  192. const deps = credentialDeps({
  193. settings: {
  194. providerFamilyDomain: scenario.family,
  195. providerFamilyConnectionSelections: {
  196. [scenario.family]: scenario.selection,
  197. },
  198. },
  199. accountProviders: accountProvider(
  200. scenario.providerId,
  201. {
  202. type: "zhipu-account",
  203. family: scenario.family,
  204. planKind: scenario.selection.kind,
  205. ...(scenario.selection.kind === "team-coding-plan"
  206. ? {
  207. productId: scenario.selection.productId,
  208. organizationId: scenario.selection.organizationId,
  209. projectId: scenario.selection.projectId,
  210. }
  211. : {}),
  212. } as ZCodeAccountAccess,
  213. scenario.apiKey,
  214. ),
  215. });
  216. const credentials = await resolveOffPeakCredentials(deps);
  217. expect(credentials).toMatchObject({
  218. jwt: "zcode-jwt",
  219. codingPlanApiKey: scenario.apiKey,
  220. kind: scenario.kind,
  221. providerFamily: scenario.family,
  222. providerId: scenario.providerId,
  223. });
  224. await expect(resolveOffPeakCodingPlanSupport(deps)).resolves.toEqual({
  225. supported: true,
  226. kind: scenario.kind,
  227. providerFamily: scenario.family,
  228. providerId: scenario.providerId,
  229. });
  230. const requestAuth = buildOffPeakRequestAuth({
  231. credentials,
  232. ticketId: "ticket-1",
  233. });
  234. expect(requestAuth.headers).toMatchObject({
  235. Authorization: "Bearer zcode-jwt",
  236. "X-Coding-Plan-Api-Key": scenario.apiKey,
  237. "X-Off-Peak-Ticket-ID": "ticket-1",
  238. });
  239. });
  240. it("BigModel Team 从结构化连接快照向 messages 注入 organization/project", async () => {
  241. const selection = {
  242. kind: "team-coding-plan",
  243. productId: "team-pro",
  244. organizationId: "org-1",
  245. projectId: "project-1",
  246. } as const;
  247. const deps = credentialDeps({
  248. settings: {
  249. providerFamilyDomain: "bigmodel",
  250. providerFamilyConnectionSelections: { bigmodel: selection },
  251. },
  252. accountProviders: accountProvider(
  253. BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  254. {
  255. type: "zhipu-account",
  256. family: "bigmodel",
  257. planKind: "team-coding-plan",
  258. productId: selection.productId,
  259. organizationId: selection.organizationId,
  260. projectId: selection.projectId,
  261. },
  262. "team-api-key.team-secret-key",
  263. ),
  264. });
  265. const credentials = await resolveOffPeakCredentials(deps);
  266. expect(credentials).toMatchObject({
  267. kind: "bigmodel-team",
  268. organizationId: "org-1",
  269. projectId: "project-1",
  270. });
  271. const requestAuth = buildOffPeakRequestAuth({
  272. credentials,
  273. ticketId: "ticket-1",
  274. });
  275. expect(requestAuth.headers).toMatchObject({
  276. "bigmodel-organization": "org-1",
  277. "bigmodel-project": "project-1",
  278. });
  279. });
  280. it("rejects Start Plan even when another cached Coding Plan key exists", async () => {
  281. const deps = credentialDeps({
  282. settings: {
  283. providerFamilyDomain: "zai",
  284. providerFamilyConnectionSelections: { zai: { kind: "start-plan" } },
  285. },
  286. accountProviders: accountProvider(
  287. BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  288. {
  289. type: "zhipu-account",
  290. family: "zai",
  291. planKind: "start-plan",
  292. },
  293. "unselected-coding-key",
  294. ),
  295. });
  296. const error = await resolveOffPeakCredentials(deps).catch((caught: unknown) => caught);
  297. expect(error).toBeInstanceOf(OffPeakCodingPlanUnavailableError);
  298. expect((error as OffPeakCodingPlanUnavailableError).reason).toBe("start_plan_not_supported");
  299. });
  300. it("rejects when Effective Config has no current Coding Plan Account Access", async () => {
  301. const deps = credentialDeps({
  302. settings: {},
  303. accountProviders: null,
  304. });
  305. await expect(resolveOffPeakCodingPlanSupport(deps)).resolves.toEqual({
  306. supported: false,
  307. reason: "connection_unavailable",
  308. });
  309. });
  310. it("rejects a missing JWT before exposing a supported snapshot", async () => {
  311. const deps = credentialDeps({
  312. settings: {
  313. providerFamilyDomain: "bigmodel",
  314. providerFamilyConnectionSelections: {
  315. bigmodel: { kind: "individual-coding-plan" },
  316. },
  317. },
  318. accountProviders: accountProvider(
  319. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  320. individualAccess("bigmodel"),
  321. "coding-key",
  322. ),
  323. jwt: null,
  324. });
  325. await expect(resolveOffPeakCodingPlanSupport(deps)).resolves.toEqual({
  326. supported: false,
  327. reason: "jwt_missing",
  328. });
  329. });
  330. it("reports the selected connection unavailable when its request credential is missing", async () => {
  331. const deps = credentialDeps({
  332. settings: {
  333. providerFamilyDomain: "bigmodel",
  334. providerFamilyConnectionSelections: {
  335. bigmodel: { kind: "individual-coding-plan" },
  336. },
  337. },
  338. accountProviders: accountProvider(
  339. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  340. individualAccess("bigmodel"),
  341. "",
  342. ),
  343. });
  344. await expect(resolveOffPeakCodingPlanSupport(deps)).resolves.toEqual({
  345. supported: false,
  346. reason: "connection_unavailable",
  347. });
  348. });
  349. it.each([
  350. { name: "missing", activeProvider: null },
  351. { name: "different", activeProvider: "zai" },
  352. ])("rejects a $name active JWT provider identity", async ({ activeProvider }) => {
  353. const deps = credentialDeps({
  354. settings: {
  355. providerFamilyDomain: "bigmodel",
  356. providerFamilyConnectionSelections: {
  357. bigmodel: { kind: "individual-coding-plan" },
  358. },
  359. },
  360. activeProvider,
  361. accountProviders: accountProvider(
  362. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  363. individualAccess("bigmodel"),
  364. "bigmodel-coding-key",
  365. ),
  366. });
  367. await expect(resolveOffPeakCodingPlanSupport(deps)).resolves.toEqual({
  368. supported: false,
  369. reason: "provider_identity_mismatch",
  370. });
  371. });
  372. it("retries when selection changes during resolution and never mixes two selections", async () => {
  373. const zaiSettings: CredentialSettings = {
  374. providerFamilyDomain: "zai",
  375. providerFamilyConnectionSelections: { zai: { kind: "individual-coding-plan" } },
  376. };
  377. const bigmodelSettings: CredentialSettings = {
  378. providerFamilyDomain: "bigmodel",
  379. providerFamilyConnectionSelections: {
  380. bigmodel: { kind: "individual-coding-plan" },
  381. },
  382. };
  383. const deps = credentialDeps({
  384. settings: [zaiSettings, bigmodelSettings, bigmodelSettings, bigmodelSettings],
  385. accountProviders: [
  386. accountProvider(
  387. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  388. individualAccess("zai"),
  389. "zai-key",
  390. ),
  391. accountProvider(
  392. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  393. individualAccess("bigmodel"),
  394. "bigmodel-key",
  395. ),
  396. ],
  397. });
  398. await expect(resolveOffPeakCredentials(deps)).resolves.toMatchObject({
  399. providerFamily: "bigmodel",
  400. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  401. codingPlanApiKey: "bigmodel-key",
  402. });
  403. });
  404. });