zcode-builtin-release.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { basename, dirname, join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. ProviderConfigService,
  7. ProviderRegistryService,
  8. createFailClosedAccountProviderConfigSnapshot,
  9. } from "@zcode/provider";
  10. import {
  11. NodeZCodeBuiltinProviderConfigSource,
  12. EndpointScopedZCodeBuiltinSource,
  13. ZCodeBuiltinRemoteSynchronizer,
  14. decodeZCodeBuiltinRelease,
  15. encodeZCodeBuiltinRelease,
  16. resolveZCodeBuiltinCachePaths,
  17. NodePersonalProviderConfigRepository,
  18. } from "../src/index.js";
  19. const roots: string[] = [];
  20. afterEach(async () => {
  21. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  22. });
  23. describe("ZCode Built-in Release", () => {
  24. it("失败按 1/2/4 分钟退避并封顶一小时;日志区分未到期与 lease", async () => {
  25. const root = await temporaryRoot();
  26. const bundledFilePath = join(root, "bundled.json");
  27. const controlFilePath = join(root, "control.json");
  28. await writeRelease(bundledFilePath, 1, "model-a");
  29. const source = new NodeZCodeBuiltinProviderConfigSource({ bundledFilePath, watch: false });
  30. let now = 1000;
  31. const events = vi.fn();
  32. const fetchRelease = vi.fn(async () => {
  33. throw new Error("offline");
  34. });
  35. const sync = new ZCodeBuiltinRemoteSynchronizer({
  36. source,
  37. controlFilePath,
  38. resolveEndpointKey: () => "https://example.com",
  39. fetchRelease,
  40. now: () => now,
  41. onRefreshResult: events,
  42. });
  43. try {
  44. for (const minutes of [1, 2, 4, 8, 16, 32, 60, 60]) {
  45. await expect(sync.refresh()).rejects.toThrow("offline");
  46. expect(JSON.parse(await readFile(controlFilePath, "utf8")).nextEligibleAt).toBe(
  47. now + minutes * 60_000,
  48. );
  49. now += minutes * 60_000 - 1;
  50. await expect(sync.refresh()).resolves.toBe("skipped");
  51. expect(events).toHaveBeenLastCalledWith({ result: "skipped", reason: "not-due" });
  52. now += 1;
  53. }
  54. await writeFile(
  55. controlFilePath,
  56. JSON.stringify({
  57. schemaVersion: 1,
  58. endpointKey: "https://example.com",
  59. leaseUntil: now + 30_000,
  60. nextEligibleAt: 0,
  61. failureCount: 0,
  62. }),
  63. );
  64. await expect(sync.refresh({ force: true })).resolves.toBe("skipped");
  65. expect(events).toHaveBeenLastCalledWith({ result: "skipped", reason: "lease-held" });
  66. expect(fetchRelease).toHaveBeenCalledTimes(8);
  67. } finally {
  68. sync.dispose();
  69. source.dispose();
  70. }
  71. });
  72. it("严格解析两层 Release,并拒绝缺字段和旧单层形状", () => {
  73. const release = decodeZCodeBuiltinRelease(releaseObject(2, "model-b"));
  74. expect(release.revision).toBe(2);
  75. expect(release.config.providers.get("builtin")?.builtinModelIds).toEqual(["model-b"]);
  76. expect(encodeZCodeBuiltinRelease(release)).toEqual(releaseObject(2, "model-b"));
  77. expect(() =>
  78. decodeZCodeBuiltinRelease({ schemaVersion: 1, providers: {}, models: [] }),
  79. ).toThrow();
  80. expect(() =>
  81. decodeZCodeBuiltinRelease({
  82. schemaVersion: 1,
  83. revision: 1,
  84. config: { providers: {} },
  85. }),
  86. ).toThrow();
  87. });
  88. it("拒绝远端或缓存重新发布已退出产品的 ZAPI", () => {
  89. const release = releaseObject(2, "model-b");
  90. expect(() =>
  91. decodeZCodeBuiltinRelease({
  92. ...release,
  93. config: {
  94. ...release.config,
  95. providerConfigRules: {
  96. ...release.config.providerConfigRules,
  97. providerRules: [
  98. ...release.config.providerConfigRules.providerRules,
  99. {
  100. providerId: "builtin:zapi",
  101. config: {
  102. group: "zai-family",
  103. access: {
  104. type: "zhipu-account",
  105. accountType: "zai",
  106. mode: "start-plan",
  107. },
  108. builtinModelIds: ["retired-model"],
  109. },
  110. },
  111. ],
  112. },
  113. },
  114. }),
  115. ).toThrow("builtin:zapi");
  116. });
  117. it("缓存路径按平台、App 版本和规范化 Endpoint 隔离", () => {
  118. const first = resolveZCodeBuiltinCachePaths({
  119. environmentConfigRoot: "/environment",
  120. platform: "darwin-aarch64",
  121. appVersion: "3.0.0",
  122. zcodeEndpointOrigin: "https://EXAMPLE.com/",
  123. });
  124. const equivalent = resolveZCodeBuiltinCachePaths({
  125. environmentConfigRoot: "/environment",
  126. platform: "darwin-aarch64",
  127. appVersion: "3.0.0",
  128. zcodeEndpointOrigin: "https://example.com",
  129. });
  130. const second = resolveZCodeBuiltinCachePaths({
  131. environmentConfigRoot: "/environment",
  132. platform: "darwin-aarch64",
  133. appVersion: "3.0.0",
  134. zcodeEndpointOrigin: "https://staging.example.com",
  135. });
  136. expect(first).toEqual(equivalent);
  137. // 路径断言保留全部隔离层级,不能用 POSIX 分隔符让 Windows 正确实现误报。
  138. expect(dirname(dirname(first.activeFilePath))).toBe(
  139. join("/environment", "runtime", "provider", "darwin-aarch64", "3.0.0"),
  140. );
  141. expect(basename(dirname(first.activeFilePath))).toMatch(/^endpoint-[a-f0-9]{32}$/u);
  142. expect(basename(first.activeFilePath)).toBe("zcode-builtin.json");
  143. expect(first.controlFilePath).toBe(
  144. join(dirname(first.activeFilePath), "zcode-builtin-refresh.json"),
  145. );
  146. expect(second.activeFilePath).not.toBe(first.activeFilePath);
  147. expect(() =>
  148. resolveZCodeBuiltinCachePaths({
  149. environmentConfigRoot: "/environment",
  150. platform: "../other",
  151. appVersion: "3.0.0",
  152. zcodeEndpointOrigin: "https://example.com",
  153. }),
  154. ).toThrow("platform");
  155. });
  156. it("启动选择兼容且 revision 最大的候选,并将它物化为活动文件", async () => {
  157. const root = await temporaryRoot();
  158. const bundledFilePath = join(root, "bundled.json");
  159. const activeFilePath = join(root, "cache", "active.json");
  160. await writeRelease(bundledFilePath, 2, "bundled-model");
  161. await writeRelease(activeFilePath, 3, "active-model");
  162. const source = new NodeZCodeBuiltinProviderConfigSource({
  163. bundledFilePath,
  164. activeFilePath,
  165. watch: false,
  166. });
  167. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual([
  168. "active-model",
  169. ]);
  170. expect(JSON.parse(await readFile(activeFilePath, "utf8"))).toEqual(
  171. releaseObject(3, "active-model"),
  172. );
  173. source.dispose();
  174. });
  175. it("损坏、过旧或不兼容 Active 不覆盖 Bundled", async () => {
  176. const root = await temporaryRoot();
  177. const bundledFilePath = join(root, "bundled.json");
  178. const activeFilePath = join(root, "cache", "active.json");
  179. await writeRelease(bundledFilePath, 4, "bundled-model");
  180. await writeRelease(activeFilePath, 3, "old-model");
  181. const source = new NodeZCodeBuiltinProviderConfigSource({
  182. bundledFilePath,
  183. activeFilePath,
  184. watch: false,
  185. });
  186. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual([
  187. "bundled-model",
  188. ]);
  189. expect(JSON.parse(await readFile(activeFilePath, "utf8"))).toEqual(
  190. releaseObject(4, "bundled-model"),
  191. );
  192. source.dispose();
  193. });
  194. it("Bundled 与 Active 的相同 revision 冲突时丢弃 Active 并以 Bundled 启动", async () => {
  195. const root = await temporaryRoot();
  196. const bundledFilePath = join(root, "bundled.json");
  197. const activeFilePath = join(root, "cache", "active.json");
  198. await writeRelease(bundledFilePath, 4, "bundled-model");
  199. await writeRelease(activeFilePath, 4, "other-model");
  200. const source = new NodeZCodeBuiltinProviderConfigSource({
  201. bundledFilePath,
  202. activeFilePath,
  203. watch: false,
  204. });
  205. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual([
  206. "bundled-model",
  207. ]);
  208. expect(JSON.parse(await readFile(activeFilePath, "utf8"))).toEqual(
  209. releaseObject(4, "bundled-model"),
  210. );
  211. source.dispose();
  212. });
  213. it("Active 缓存无法物化时仍直接使用 Bundled 完成启动", async () => {
  214. const root = await temporaryRoot();
  215. const bundledFilePath = join(root, "bundled.json");
  216. const activeFilePath = join(root, "cache", "active.json");
  217. await writeRelease(bundledFilePath, 4, "bundled-model");
  218. await mkdir(activeFilePath, { recursive: true });
  219. const source = new NodeZCodeBuiltinProviderConfigSource({
  220. bundledFilePath,
  221. activeFilePath,
  222. watch: false,
  223. });
  224. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual([
  225. "bundled-model",
  226. ]);
  227. source.dispose();
  228. });
  229. it("远端更高 revision 原子更新;同 revision 同内容去重、不同内容拒绝", async () => {
  230. const root = await temporaryRoot();
  231. const bundledFilePath = join(root, "bundled.json");
  232. const activeFilePath = join(root, "cache", "active.json");
  233. await writeRelease(bundledFilePath, 1, "model-a");
  234. const source = new NodeZCodeBuiltinProviderConfigSource({
  235. bundledFilePath,
  236. activeFilePath,
  237. watch: false,
  238. });
  239. const reasons: string[] = [];
  240. source.onDidChange((reason) => reasons.push(reason));
  241. await source.read();
  242. await expect(
  243. source.applyRemoteRelease(decodeZCodeBuiltinRelease(releaseObject(2, "model-b"))),
  244. ).resolves.toBe("updated");
  245. await expect(
  246. source.applyRemoteRelease(decodeZCodeBuiltinRelease(releaseObject(2, "model-b"))),
  247. ).resolves.toBe("unchanged");
  248. await expect(
  249. source.applyRemoteRelease(decodeZCodeBuiltinRelease(releaseObject(2, "different"))),
  250. ).rejects.toThrow("相同 revision");
  251. await expect(
  252. source.applyRemoteRelease(decodeZCodeBuiltinRelease(releaseObject(1, "old"))),
  253. ).resolves.toBe("stale");
  254. expect(reasons).toEqual(["remote-updated"]);
  255. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual(["model-b"]);
  256. source.dispose();
  257. });
  258. it("多个同步器通过落盘 lease 合并请求,并按 endpoint 隔离 TTL", async () => {
  259. const root = await temporaryRoot();
  260. const bundledFilePath = join(root, "bundled.json");
  261. const activeFilePath = join(root, "cache", "active.json");
  262. const controlFilePath = join(root, "cache", "refresh-control.json");
  263. await writeRelease(bundledFilePath, 1, "model-a");
  264. const source = new NodeZCodeBuiltinProviderConfigSource({
  265. bundledFilePath,
  266. activeFilePath,
  267. watch: false,
  268. });
  269. await source.read();
  270. let releaseFetch!: () => void;
  271. const fetchRelease = vi.fn(
  272. () =>
  273. new Promise<ReturnType<typeof decodeZCodeBuiltinRelease>>((resolve) => {
  274. releaseFetch = () => resolve(decodeZCodeBuiltinRelease(releaseObject(2, "model-b")));
  275. }),
  276. );
  277. const first = new ZCodeBuiltinRemoteSynchronizer({
  278. source,
  279. controlFilePath,
  280. resolveEndpointKey: () => "https://first.example.com",
  281. fetchRelease,
  282. now: () => 1_000,
  283. });
  284. const second = new ZCodeBuiltinRemoteSynchronizer({
  285. source,
  286. controlFilePath,
  287. resolveEndpointKey: () => "https://first.example.com",
  288. fetchRelease,
  289. now: () => 1_000,
  290. });
  291. const firstRefresh = first.refresh();
  292. await vi.waitFor(() => expect(fetchRelease).toHaveBeenCalledTimes(1));
  293. await expect(second.refresh()).resolves.toBe("skipped");
  294. releaseFetch();
  295. await expect(firstRefresh).resolves.toBe("updated");
  296. const endpointChangedFetch = vi.fn(async () => null);
  297. const endpointChanged = new ZCodeBuiltinRemoteSynchronizer({
  298. source,
  299. controlFilePath,
  300. resolveEndpointKey: () => "https://second.example.com",
  301. fetchRelease: endpointChangedFetch,
  302. now: () => 1_001,
  303. });
  304. await expect(endpointChanged.refresh()).resolves.toBe("missing");
  305. expect(endpointChangedFetch).toHaveBeenCalledOnce();
  306. first.dispose();
  307. second.dispose();
  308. endpointChanged.dispose();
  309. source.dispose();
  310. });
  311. it("Endpoint 切换后丢弃旧 Endpoint 的晚到响应", async () => {
  312. const root = await temporaryRoot();
  313. const bundledFilePath = join(root, "bundled.json");
  314. const activeFilePath = join(root, "cache", "active.json");
  315. await writeRelease(bundledFilePath, 1, "model-a");
  316. const source = new NodeZCodeBuiltinProviderConfigSource({
  317. bundledFilePath,
  318. activeFilePath,
  319. watch: false,
  320. });
  321. await source.read();
  322. let endpointKey = "https://old.example.com";
  323. let completeFetch!: () => void;
  324. const synchronizer = new ZCodeBuiltinRemoteSynchronizer({
  325. source,
  326. controlFilePath: join(root, "cache", "refresh-control.json"),
  327. resolveEndpointKey: () => endpointKey,
  328. fetchRelease: () =>
  329. new Promise((resolve) => {
  330. completeFetch = () =>
  331. resolve(decodeZCodeBuiltinRelease(releaseObject(2, "old-endpoint-model")));
  332. }),
  333. });
  334. const refresh = synchronizer.refresh();
  335. await vi.waitFor(() => expect(completeFetch).toBeTypeOf("function"));
  336. endpointKey = "https://new.example.com";
  337. completeFetch();
  338. await expect(refresh).resolves.toBe("skipped");
  339. expect(JSON.parse(await readFile(activeFilePath, "utf8"))).toEqual(releaseObject(1, "model-a"));
  340. synchronizer.dispose();
  341. source.dispose();
  342. });
  343. it("不同 Endpoint 使用独立 Active/LKG,不做跨 Endpoint revision 比较", async () => {
  344. const root = await temporaryRoot();
  345. const bundledFilePath = join(root, "bundled.json");
  346. await writeRelease(bundledFilePath, 1, "bundled-model");
  347. let endpointOrigin = "https://a.example.com";
  348. const source = new EndpointScopedZCodeBuiltinSource({
  349. bundledFilePath,
  350. environmentConfigRoot: join(root, "environment"),
  351. platform: "darwin-aarch64",
  352. appVersion: "3.0.0",
  353. resolveEndpointOrigin: () => endpointOrigin,
  354. fetchRelease: async (origin) =>
  355. decodeZCodeBuiltinRelease(
  356. origin === "https://a.example.com"
  357. ? releaseObject(20, "endpoint-a-model")
  358. : releaseObject(10, "endpoint-b-model"),
  359. ),
  360. watch: false,
  361. });
  362. await expect(source.refresh({ force: true })).resolves.toBe("updated");
  363. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual([
  364. "endpoint-a-model",
  365. ]);
  366. endpointOrigin = "https://b.example.com";
  367. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual([
  368. "bundled-model",
  369. ]);
  370. await expect(source.refresh({ force: true })).resolves.toBe("updated");
  371. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual([
  372. "endpoint-b-model",
  373. ]);
  374. endpointOrigin = "https://a.example.com";
  375. expect((await source.read()).providers.get("builtin")?.builtinModelIds).toEqual([
  376. "endpoint-a-model",
  377. ]);
  378. source.dispose();
  379. });
  380. it("相同发布序号跨 Endpoint 仍更新完整 Registry,Host 与 Worker 使用同一来源标识", async () => {
  381. const root = await temporaryRoot();
  382. const bundledFilePath = join(root, "bundled.json");
  383. await writeRelease(bundledFilePath, 1, "bundled");
  384. let endpoint = "https://a.example.com";
  385. const source = new EndpointScopedZCodeBuiltinSource({
  386. bundledFilePath,
  387. environmentConfigRoot: root,
  388. platform: "darwin-aarch64",
  389. appVersion: "3.12.0",
  390. resolveEndpointOrigin: () => endpoint,
  391. fetchRelease: async (origin) =>
  392. decodeZCodeBuiltinRelease(
  393. releaseObject(20, origin.includes("a.example") ? "model-a" : "model-b"),
  394. ),
  395. watch: false,
  396. });
  397. const personal = new NodePersonalProviderConfigRepository({
  398. filePath: join(root, "personal.json"),
  399. pollingIntervalMs: false,
  400. });
  401. const config = new ProviderConfigService({
  402. zcodeBuiltinSource: source,
  403. personalRepository: personal,
  404. });
  405. const registry = new ProviderRegistryService({
  406. configSource: config,
  407. accountSource: {
  408. read: async () => createFailClosedAccountProviderConfigSnapshot(await config.read()),
  409. onDidChange: () => () => {},
  410. },
  411. });
  412. try {
  413. await source.refresh({ force: true });
  414. await registry.start();
  415. const first = registry.getSnapshot()!;
  416. endpoint = "https://b.example.com";
  417. await source.refresh({ force: true });
  418. const second = await registry.refresh("endpoint-switch");
  419. expect(second.sourceRevisions.config).not.toBe(first.sourceRevisions.config);
  420. expect(second.account.basedOnZCodeBuiltinRevision).toBe(second.config.zcodeBuiltinRevision);
  421. expect(second.resolution.resolvedProviders[0]?.models.map((model) => model.modelId)).toEqual([
  422. "model-b",
  423. ]);
  424. const activeFilePath = await source.resolveActiveFilePath();
  425. const worker = new NodeZCodeBuiltinProviderConfigSource({
  426. bundledFilePath: activeFilePath,
  427. watch: false,
  428. });
  429. try {
  430. expect((await worker.read()).revision).toBe(second.config.zcodeBuiltinRevision);
  431. } finally {
  432. worker.dispose();
  433. }
  434. endpoint = "https://A.example.com/";
  435. expect((await source.read()).revision).toBe(first.config.zcodeBuiltinRevision);
  436. // 等待来源通知触发的刷新完成后再拆除临时目录,不与后台文件锁竞争清理。
  437. await registry.refresh("endpoint-back");
  438. } finally {
  439. registry.dispose();
  440. config.dispose();
  441. personal.dispose();
  442. source.dispose();
  443. }
  444. });
  445. it("有效 lease 连显式刷新也不能绕过,过期后可接管", async () => {
  446. const root = await temporaryRoot();
  447. const bundledFilePath = join(root, "bundled.json");
  448. const activeFilePath = join(root, "cache", "active.json");
  449. const controlFilePath = join(root, "cache", "refresh-control.json");
  450. await writeRelease(bundledFilePath, 1, "model-a");
  451. await mkdir(dirname(controlFilePath), { recursive: true });
  452. await writeFile(
  453. controlFilePath,
  454. JSON.stringify({
  455. schemaVersion: 1,
  456. endpointKey: "https://example.com",
  457. leaseId: "crashed-owner",
  458. leaseUntil: 2_000,
  459. nextEligibleAt: 0,
  460. failureCount: 0,
  461. }),
  462. );
  463. const source = new NodeZCodeBuiltinProviderConfigSource({
  464. bundledFilePath,
  465. activeFilePath,
  466. watch: false,
  467. });
  468. await source.read();
  469. let now = 1_000;
  470. const fetchRelease = vi.fn(async () => null);
  471. const synchronizer = new ZCodeBuiltinRemoteSynchronizer({
  472. source,
  473. controlFilePath,
  474. resolveEndpointKey: () => "https://example.com",
  475. fetchRelease,
  476. now: () => now,
  477. });
  478. await expect(synchronizer.refresh({ force: true })).resolves.toBe("skipped");
  479. now = 2_001;
  480. await expect(synchronizer.refresh()).resolves.toBe("missing");
  481. expect(fetchRelease).toHaveBeenCalledOnce();
  482. synchronizer.dispose();
  483. source.dispose();
  484. });
  485. it("失败进入递增退避,显式刷新只绕过 nextEligibleAt", async () => {
  486. const root = await temporaryRoot();
  487. const bundledFilePath = join(root, "bundled.json");
  488. const activeFilePath = join(root, "cache", "active.json");
  489. const controlFilePath = join(root, "cache", "refresh-control.json");
  490. await writeRelease(bundledFilePath, 1, "model-a");
  491. const source = new NodeZCodeBuiltinProviderConfigSource({
  492. bundledFilePath,
  493. activeFilePath,
  494. watch: false,
  495. });
  496. await source.read();
  497. let now = 1_000;
  498. const fetchRelease = vi
  499. .fn<() => Promise<ReturnType<typeof decodeZCodeBuiltinRelease> | null>>()
  500. .mockRejectedValueOnce(new Error("temporary"))
  501. .mockResolvedValue(null);
  502. const synchronizer = new ZCodeBuiltinRemoteSynchronizer({
  503. source,
  504. controlFilePath,
  505. resolveEndpointKey: () => "https://example.com",
  506. fetchRelease,
  507. now: () => now,
  508. failureBaseDelayMs: 100,
  509. });
  510. await expect(synchronizer.refresh()).rejects.toThrow("temporary");
  511. now = 1_050;
  512. await expect(synchronizer.refresh()).resolves.toBe("skipped");
  513. await expect(synchronizer.refresh({ force: true })).resolves.toBe("missing");
  514. expect(fetchRelease).toHaveBeenCalledTimes(2);
  515. synchronizer.dispose();
  516. source.dispose();
  517. });
  518. it("dispose 后到达的远端响应不写入 Active", async () => {
  519. const root = await temporaryRoot();
  520. const bundledFilePath = join(root, "bundled.json");
  521. const activeFilePath = join(root, "cache", "active.json");
  522. await writeRelease(bundledFilePath, 1, "model-a");
  523. const source = new NodeZCodeBuiltinProviderConfigSource({
  524. bundledFilePath,
  525. activeFilePath,
  526. watch: false,
  527. });
  528. await source.read();
  529. let completeFetch!: () => void;
  530. const synchronizer = new ZCodeBuiltinRemoteSynchronizer({
  531. source,
  532. controlFilePath: join(root, "cache", "refresh-control.json"),
  533. resolveEndpointKey: () => "https://example.com",
  534. fetchRelease: () =>
  535. new Promise((resolve) => {
  536. completeFetch = () => resolve(decodeZCodeBuiltinRelease(releaseObject(2, "model-b")));
  537. }),
  538. });
  539. const refresh = synchronizer.refresh();
  540. await vi.waitFor(() => expect(completeFetch).toBeTypeOf("function"));
  541. synchronizer.dispose();
  542. completeFetch();
  543. await expect(refresh).resolves.toBe("disposed");
  544. expect(JSON.parse(await readFile(activeFilePath, "utf8"))).toEqual(releaseObject(1, "model-a"));
  545. source.dispose();
  546. });
  547. });
  548. async function temporaryRoot(): Promise<string> {
  549. const root = await mkdtemp(join(tmpdir(), "zcode-builtin-release-"));
  550. roots.push(root);
  551. return root;
  552. }
  553. async function writeRelease(filePath: string, revision: number, modelId: string): Promise<void> {
  554. await mkdir(dirname(filePath), { recursive: true });
  555. await writeFile(filePath, JSON.stringify(releaseObject(revision, modelId)), "utf8");
  556. }
  557. function releaseObject(revision: number, modelId: string) {
  558. return {
  559. schemaVersion: 1,
  560. revision,
  561. config: {
  562. providerConfigRules: {
  563. providerRules: [
  564. {
  565. providerId: "builtin",
  566. config: {
  567. group: "zai-family",
  568. access: {
  569. type: "zhipu-account",
  570. accountType: "zai",
  571. mode: "start-plan",
  572. },
  573. builtinModelIds: [modelId],
  574. },
  575. },
  576. ],
  577. templateRules: [],
  578. },
  579. modelConfigRules: {
  580. modelRules: [],
  581. modelApiRules: [],
  582. providerSiteRules: [],
  583. templateModelRules: [],
  584. builtinProviderModelRules: [],
  585. },
  586. },
  587. };
  588. }