offPeakRuntimeModel.test.ts 13 KB

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