providerProvisioningRealStores.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. AccountProviderService,
  7. ModelConfig,
  8. ModelConfigRules,
  9. ModelOptionSpecsConfig,
  10. ModelPropertiesConfig,
  11. ProviderConfigMap,
  12. parsePersonalProviderConfigMap,
  13. resolveInitialModelSelection,
  14. } from "@zcode/provider";
  15. import { encodeProviderConfigFile, NodeModelSelectionConfigRepository } from "@zcode/provider-node";
  16. import type { ProviderProvisioningEnvelope } from "@zcode/shared";
  17. import { createCredentialService } from "../src/credential/credentialService.js";
  18. import { createCredentialCipherProvider } from "../src/credential/providers/credentialCipherProvider.js";
  19. import { createSettingService } from "../src/setting/settingService.js";
  20. import { getDataBaseDir, setDataBaseDir } from "../src/paths.js";
  21. import { createProviderConfigRuntime } from "../src/model-provider/providerConfigRuntime.js";
  22. import { createProviderRuntimeFromConfigRuntime } from "../src/model-provider/providerRuntime.js";
  23. import { createProviderProvisioningTarget } from "../src/model-provider/providerProvisioningTarget.js";
  24. const selection = {
  25. providerId: "r3-store",
  26. modelId: "r3-model",
  27. options: { reasoningLevel: "disabled" },
  28. };
  29. function providerEntry(key: string, modelId = "r3-model") {
  30. return {
  31. providerId: "r3-store",
  32. config: {
  33. group: "standard-personal",
  34. access: { type: "api-key", apiKey: key },
  35. api: { type: "openai-chat-completions", baseUrl: "http://127.0.0.1:1/v1" },
  36. personalModelIds: [modelId],
  37. },
  38. };
  39. }
  40. function completeModel() {
  41. return new ModelConfig({
  42. enabled: true,
  43. properties: new ModelPropertiesConfig({
  44. requiresMfjsToolSchema: false,
  45. contextWindow: 32_000,
  46. inputFormat: {
  47. supportsText: true,
  48. supportsImage: false,
  49. supportsVideo: false,
  50. supportsAudio: false,
  51. supportsPdf: false,
  52. },
  53. outputFormat: { supportsText: true },
  54. supportsToolCall: true,
  55. supportsJsonSchemaOutput: false,
  56. supportsNativeWebSearch: false,
  57. supportsMidConversationSystem: false,
  58. }),
  59. optionSpecs: new ModelOptionSpecsConfig({
  60. reasoningLevel: { values: ["disabled"], map: "{}" },
  61. maxOutputTokens: { max: 4096, map: '{"max_tokens":maxOutputTokens}' },
  62. }),
  63. });
  64. }
  65. function envelope(syncId: string, key: string): ProviderProvisioningEnvelope {
  66. const config = encodeProviderConfigFile({
  67. providers: parsePersonalProviderConfigMap({ providerRules: [providerEntry(key)] }),
  68. models: ModelConfigRules.empty().setExact("r3-store", "r3-model", completeModel()),
  69. providerOrder: ["r3-store"],
  70. // 只有基线信封携带默认选择;后续失败信封会清默认,回滚必须把它一起复原。
  71. ...(syncId === "baseline" ? { defaultModelSelection: selection } : {}),
  72. });
  73. return {
  74. schemaVersion: 1,
  75. syncId,
  76. personalConfig: config.config,
  77. accountSettings: {
  78. providerFamilyDomain: syncId === "baseline" ? "bigmodel" : "zai",
  79. providerFamilyConnectionSelections: {},
  80. },
  81. credentials: [{ scope: "oauth-session", key: "oauth:zai:access_token", value: key }],
  82. };
  83. }
  84. async function createFixture(root: string) {
  85. setDataBaseDir(root);
  86. // 设置服务独立读取HOME;仅在Vitest worker中模拟系统用户目录,避免触及真实用户设置。
  87. vi.stubEnv("HOME", root);
  88. const dir = join(root, ".zcode/v2");
  89. await mkdir(dir, { recursive: true });
  90. const builtin = join(root, "builtin.json");
  91. await writeFile(
  92. builtin,
  93. JSON.stringify({
  94. schemaVersion: 1,
  95. revision: 1,
  96. config: {
  97. providerConfigRules: { templateRules: [], providerRules: [] },
  98. modelConfigRules: {
  99. modelRules: [],
  100. modelApiRules: [],
  101. providerSiteRules: [],
  102. templateModelRules: [],
  103. builtinProviderModelRules: [],
  104. },
  105. },
  106. }),
  107. );
  108. const personal = join(dir, "provider_config.json");
  109. const state = join(dir, "provisioning-state.json");
  110. const config = createProviderConfigRuntime({
  111. zcodeBuiltinFilePath: builtin,
  112. personalFilePath: personal,
  113. watch: false,
  114. personalPollingIntervalMs: false,
  115. });
  116. // 本测试无账号Provider;权益解析固定为空,事务与Registry、四类Store均使用真实实现。
  117. const account = new AccountProviderService({
  118. configSource: config.configService,
  119. resolve: async () => ({ providers: ProviderConfigMap.empty(), states: {} }),
  120. });
  121. const runtime = createProviderRuntimeFromConfigRuntime({
  122. configRuntime: config,
  123. accountSource: account,
  124. });
  125. // 默认选择只是 Personal 文件的一个字段,与 Provisioning 走同一份 Repository。
  126. const defaults = new NodeModelSelectionConfigRepository({
  127. personalRepository: config.personalRepository,
  128. });
  129. const credentials = createCredentialService({
  130. cipherProvider: createCredentialCipherProvider({
  131. env: { ZCODE_CREDENTIAL_SECRET: "r3-real-stores-test-cipher" },
  132. }),
  133. });
  134. const settings = createSettingService();
  135. const target = createProviderProvisioningTarget({
  136. providerRuntime: runtime,
  137. personalRepository: config.personalRepository,
  138. accountProviderSource: account,
  139. credentialService: credentials,
  140. settingService: settings,
  141. personalConfigFilePath: personal,
  142. stateFilePath: state,
  143. listProvisioningCredentialKeys: async () => ["oauth:zai:access_token"],
  144. });
  145. await settings.update({ locale: "en-US", providerFamilyDomain: "bigmodel" });
  146. await credentials.save("ssh:r3-sentinel", "not-provisioned");
  147. const baseline = await target.apply(envelope("baseline", "old-value"));
  148. expect(baseline).toMatchObject({ status: "applied" });
  149. return {
  150. runtime,
  151. account,
  152. defaults,
  153. personalRepository: config.personalRepository,
  154. credentials,
  155. settings,
  156. target,
  157. state,
  158. personal,
  159. dir,
  160. builtin,
  161. dispose() {
  162. runtime.dispose();
  163. account.dispose();
  164. defaults.dispose();
  165. },
  166. };
  167. }
  168. describe("R3A-PRV-08/09 正式磁盘Store与Registry事务", () => {
  169. let root: string;
  170. let previousRoot: string;
  171. let fixture: Awaited<ReturnType<typeof createFixture>>;
  172. beforeEach(async () => {
  173. previousRoot = getDataBaseDir();
  174. root = await mkdtemp(join(tmpdir(), "r3-provisioning-stores-"));
  175. fixture = await createFixture(root);
  176. });
  177. afterEach(async () => {
  178. vi.restoreAllMocks();
  179. fixture?.dispose();
  180. setDataBaseDir(previousRoot);
  181. vi.unstubAllEnvs();
  182. if (root) await rm(root, { recursive: true, force: true });
  183. });
  184. it.each(["settings", "credentials", "personal"] as const)(
  185. "PRV-08 %s提交后报错,逆序恢复正式存储及内存Registry",
  186. async (stage) => {
  187. const before = await readFile(fixture.personal, "utf8");
  188. const builtin = await readFile(fixture.builtin, "utf8");
  189. const inject = <T extends object, K extends keyof T>(object: T, key: K) => {
  190. const original = object[key] as (...args: unknown[]) => Promise<unknown>;
  191. vi.spyOn(object, key as never).mockImplementationOnce((async (...args: unknown[]) => {
  192. await original.apply(object, args);
  193. throw new Error(`R3_FAULT_AFTER_${stage}`);
  194. }) as never);
  195. };
  196. if (stage === "settings") inject(fixture.settings, "update");
  197. if (stage === "credentials") inject(fixture.credentials, "save");
  198. if (stage === "personal") inject(fixture.personalRepository, "update");
  199. const result = await fixture.target.apply(envelope(`fail-${stage}`, "new-value"));
  200. expect(result).toMatchObject({ status: "failed", rolledBack: true });
  201. expect(await readFile(fixture.personal, "utf8")).toBe(before);
  202. expect(await fixture.defaults.read()).toEqual(selection);
  203. expect(await fixture.credentials.load("oauth:zai:access_token")).toBe("old-value");
  204. expect(await fixture.credentials.load("ssh:r3-sentinel")).toBe("not-provisioned");
  205. expect(await fixture.settings.get()).toMatchObject({
  206. locale: "en-US",
  207. providerFamilyDomain: "bigmodel",
  208. });
  209. expect(fixture.runtime.registryService.validateSelection(selection).ok).toBe(true);
  210. const snapshot = await fixture.runtime.configService.read();
  211. expect(snapshot.personalProviders.get("r3-store")?.access).toMatchObject({
  212. apiKey: "old-value",
  213. });
  214. expect(await readFile(fixture.builtin, "utf8")).toBe(builtin);
  215. expect(await readFile(fixture.state, "utf8")).not.toContain(`fail-${stage}`);
  216. expect(await readFile(join(fixture.dir, "credentials.json"), "utf8")).not.toContain(
  217. "old-value",
  218. );
  219. },
  220. );
  221. it("PRV-09 丢弃ACK后同syncId重试,再重放更早syncId不会覆盖新配置", async () => {
  222. await fixture.target.apply(envelope("ack-lost", "middle-value"));
  223. const stateAfterCommit = await readFile(fixture.state, "utf8");
  224. expect((await fixture.target.apply(envelope("ack-lost", "middle-value"))).status).toBe(
  225. "already-applied",
  226. );
  227. expect(await readFile(fixture.state, "utf8")).toBe(stateAfterCommit);
  228. expect((await fixture.target.apply(envelope("newest", "newest-value"))).status).toBe("applied");
  229. const after = await readFile(fixture.personal, "utf8");
  230. expect((await fixture.target.apply(envelope("ack-lost", "middle-value"))).status).toBe(
  231. "already-applied",
  232. );
  233. expect(await readFile(fixture.personal, "utf8")).toBe(after);
  234. expect(await fixture.credentials.load("oauth:zai:access_token")).toBe("newest-value");
  235. expect(fixture.runtime.registryService.validateSelection(selection).ok).toBe(true);
  236. expect(JSON.parse(await readFile(fixture.state, "utf8")).records).toHaveLength(3);
  237. });
  238. it("PRV-08 回滚自身失败时返回rollback_failed且不登记成功", async () => {
  239. const update = fixture.personalRepository.update.bind(fixture.personalRepository);
  240. vi.spyOn(fixture.personalRepository, "update")
  241. .mockImplementationOnce(async (mutate) => {
  242. const snapshot = await update(mutate);
  243. throw Object.assign(new Error("R3_AFTER_COMMIT"), { snapshot });
  244. })
  245. .mockRejectedValue(new Error("R3_ROLLBACK_DISK_FAILURE"));
  246. const result = await fixture.target.apply(envelope("rollback-failed", "new-value"));
  247. expect(result).toMatchObject({ status: "rollback_failed", rolledBack: false });
  248. expect(await readFile(fixture.state, "utf8")).not.toContain("rollback-failed");
  249. });
  250. });
  251. // R3A-PRV-05/06/07/10/11 与 PRV-02 的 Target 侧状态:同一真实 Store/Registry fixture。
  252. function customEnvelope(
  253. syncId: string,
  254. input: {
  255. providerRules: readonly ReturnType<typeof providerEntry>[];
  256. models?: ModelConfigRules;
  257. defaultModelSelection?: typeof selection | undefined;
  258. credentials?: ProviderProvisioningEnvelope["credentials"];
  259. accountSettings?: ProviderProvisioningEnvelope["accountSettings"];
  260. },
  261. ): ProviderProvisioningEnvelope {
  262. const config = encodeProviderConfigFile({
  263. providers: parsePersonalProviderConfigMap({ providerRules: input.providerRules }),
  264. models: input.models ?? ModelConfigRules.empty(),
  265. providerOrder: input.providerRules.map((rule) => rule.providerId),
  266. ...(input.defaultModelSelection ? { defaultModelSelection: input.defaultModelSelection } : {}),
  267. });
  268. return {
  269. schemaVersion: 1,
  270. syncId,
  271. personalConfig: config.config,
  272. accountSettings: input.accountSettings ?? {
  273. providerFamilyDomain: "bigmodel",
  274. providerFamilyConnectionSelections: {},
  275. },
  276. credentials: input.credentials ?? [
  277. { scope: "oauth-session", key: "oauth:zai:access_token", value: "old-value" },
  278. ],
  279. };
  280. }
  281. function brokenProviderEntry(key: string) {
  282. return {
  283. providerId: "r3-broken",
  284. config: {
  285. group: "standard-personal",
  286. access: { type: "api-key", apiKey: key },
  287. api: { type: "openai-chat-completions", baseUrl: "http://127.0.0.1:1/v1" },
  288. personalModelIds: ["broken-model"],
  289. },
  290. };
  291. }
  292. describe("R3A-PRV-05/06/07/10/11 完整替换、allowlist 凭据、窄设置与无效配置", () => {
  293. let root: string;
  294. let previousRoot: string;
  295. let fixture: Awaited<ReturnType<typeof createFixture>>;
  296. beforeEach(async () => {
  297. previousRoot = getDataBaseDir();
  298. root = await mkdtemp(join(tmpdir(), "r3-provisioning-stores-b-"));
  299. fixture = await createFixture(root);
  300. });
  301. afterEach(async () => {
  302. vi.restoreAllMocks();
  303. fixture?.dispose();
  304. setDataBaseDir(previousRoot);
  305. vi.unstubAllEnvs();
  306. if (root) await rm(root, { recursive: true, force: true });
  307. });
  308. it("PRV-05 本地删除 provider 后完整替换:目标不保留被删镜像,空配置也真实写入", async () => {
  309. const result = await fixture.target.apply(
  310. customEnvelope("delete-provider", { providerRules: [], defaultModelSelection: undefined }),
  311. );
  312. expect(result).toMatchObject({ status: "applied", personalProviderCount: 0 });
  313. const snapshot = await fixture.runtime.configService.read();
  314. expect(snapshot.personalProviders.keys()).toHaveLength(0);
  315. expect(await fixture.defaults.read()).toBeUndefined();
  316. expect(await readFile(fixture.personal, "utf8")).not.toContain("r3-store");
  317. expect(fixture.runtime.registryService.validateSelection(selection).ok).toBe(false);
  318. });
  319. it("PRV-05 删除 provider 后完整替换并保留失效默认,空 Registry 不伪造推荐", async () => {
  320. const input = customEnvelope("delete-but-default", {
  321. providerRules: [],
  322. defaultModelSelection: selection,
  323. });
  324. const result = await fixture.target.apply(input);
  325. // 默认偏好已与同步成功解耦;旧断言遗漏该契约更新,错误要求恢复已删除的 Provider。
  326. expect(result).toMatchObject({
  327. status: "applied",
  328. rolledBack: false,
  329. personalProviderCount: 0,
  330. });
  331. expect(JSON.parse(await readFile(fixture.personal, "utf8")).config).toEqual(
  332. input.personalConfig,
  333. );
  334. expect((await fixture.runtime.configService.read()).personalProviders.keys()).toEqual([]);
  335. expect(await fixture.defaults.read()).toEqual(selection);
  336. expect(fixture.runtime.registryService.validateSelection(selection).ok).toBe(false);
  337. expect(
  338. resolveInitialModelSelection({
  339. configuredDefault: await fixture.defaults.read(),
  340. registry: fixture.runtime.registryService.getView(),
  341. }),
  342. ).toEqual({ source: "none" });
  343. });
  344. it("PRV-05 清除默认(default undefined)只清默认,provider 保留", async () => {
  345. const result = await fixture.target.apply(
  346. customEnvelope("clear-default", {
  347. providerRules: [providerEntry("old-value")],
  348. models: ModelConfigRules.empty().setExact("r3-store", "r3-model", completeModel()),
  349. defaultModelSelection: undefined,
  350. }),
  351. );
  352. expect(result.status).toBe("applied");
  353. expect(await fixture.defaults.read()).toBeUndefined();
  354. expect(fixture.runtime.registryService.validateSelection(selection).ok).toBe(true);
  355. });
  356. it("PRV-06 allowlist 凭据同名删除传播、新值经目标 cipher 重加密;非 allowlist 凭据不变", async () => {
  357. await fixture.credentials.save("mcp:oauth:r3:token", "mcp-not-allowlisted");
  358. const result = await fixture.target.apply(
  359. customEnvelope("cred-delete", {
  360. providerRules: [providerEntry("old-value")],
  361. models: ModelConfigRules.empty().setExact("r3-store", "r3-model", completeModel()),
  362. defaultModelSelection: selection,
  363. credentials: [],
  364. }),
  365. );
  366. expect(result).toMatchObject({ status: "applied", credentialCount: 0 });
  367. expect(await fixture.credentials.load("oauth:zai:access_token")).toBeNull();
  368. expect(await fixture.credentials.load("ssh:r3-sentinel")).toBe("not-provisioned");
  369. expect(await fixture.credentials.load("mcp:oauth:r3:token")).toBe("mcp-not-allowlisted");
  370. const restored = await fixture.target.apply(
  371. customEnvelope("cred-restore", {
  372. providerRules: [providerEntry("old-value")],
  373. models: ModelConfigRules.empty().setExact("r3-store", "r3-model", completeModel()),
  374. defaultModelSelection: selection,
  375. credentials: [
  376. { scope: "oauth-session", key: "oauth:zai:access_token", value: "re-encrypted" },
  377. ],
  378. }),
  379. );
  380. expect(restored.status).toBe("applied");
  381. expect(await fixture.credentials.load("oauth:zai:access_token")).toBe("re-encrypted");
  382. const raw = await readFile(join(fixture.dir, "credentials.json"), "utf8");
  383. expect(raw).not.toContain("re-encrypted");
  384. expect(raw).not.toContain("mcp-not-allowlisted");
  385. });
  386. it("PRV-07 只改约定的账号窄字段,locale 等其它设置与 Built-in 文件不变", async () => {
  387. await fixture.settings.update({ locale: "zh-CN", terminalInheritSystemProfile: false });
  388. const builtinBefore = await readFile(fixture.builtin, "utf8");
  389. const result = await fixture.target.apply(
  390. customEnvelope("narrow-settings", {
  391. providerRules: [providerEntry("old-value")],
  392. models: ModelConfigRules.empty().setExact("r3-store", "r3-model", completeModel()),
  393. defaultModelSelection: selection,
  394. accountSettings: {
  395. providerFamilyDomain: "zai",
  396. providerFamilyConnectionSelections: { zai: { kind: "individual-coding-plan" } },
  397. },
  398. }),
  399. );
  400. expect(result.status).toBe("applied");
  401. const settings = await fixture.settings.get();
  402. expect(settings).toMatchObject({
  403. locale: "zh-CN",
  404. terminalInheritSystemProfile: false,
  405. providerFamilyDomain: "zai",
  406. providerFamilyConnectionSelections: { zai: { kind: "individual-coding-plan" } },
  407. });
  408. expect(await readFile(fixture.builtin, "utf8")).toBe(builtinBefore);
  409. });
  410. it("PRV-11 合法 provider 可用、无效项 fail-closed;保留失效默认并推荐合法模型", async () => {
  411. // r3-broken 只有 enabled,缺 maxOutputTokens;空 Built-in 层下必须被 Registry 拒绝。
  412. const models = () =>
  413. ModelConfigRules.empty()
  414. .setExact("r3-store", "r3-model", completeModel())
  415. .setExact("r3-broken", "broken-model", new ModelConfig({ enabled: true }));
  416. const applied = await fixture.target.apply(
  417. customEnvelope("mixed-valid", {
  418. providerRules: [providerEntry("old-value"), brokenProviderEntry("old-value")],
  419. models: models(),
  420. defaultModelSelection: selection,
  421. }),
  422. );
  423. expect(applied).toMatchObject({ status: "applied", personalProviderCount: 2 });
  424. expect(fixture.runtime.registryService.validateSelection(selection).ok).toBe(true);
  425. expect(
  426. fixture.runtime.registryService.validateSelection({
  427. providerId: "r3-broken",
  428. modelId: "broken-model",
  429. options: { reasoningLevel: "disabled" },
  430. }).ok,
  431. ).toBe(false);
  432. const snapshot = await fixture.runtime.configService.read();
  433. expect(snapshot.personalProviders.keys()).toEqual(
  434. expect.arrayContaining(["r3-store", "r3-broken"]),
  435. );
  436. const invalidSelection = {
  437. providerId: "r3-broken",
  438. modelId: "broken-model",
  439. options: { reasoningLevel: "disabled" },
  440. };
  441. const input = customEnvelope("mixed-broken-default", {
  442. providerRules: [providerEntry("old-value"), brokenProviderEntry("old-value")],
  443. models: models(),
  444. defaultModelSelection: invalidSelection,
  445. });
  446. const brokenDefault = await fixture.target.apply(input);
  447. // 失效偏好需要原样复制,但不授予模型执行能力;推荐只由 Host 现有解析器产生。
  448. expect(brokenDefault).toMatchObject({
  449. status: "applied",
  450. rolledBack: false,
  451. personalProviderCount: 2,
  452. });
  453. expect(JSON.parse(await readFile(fixture.personal, "utf8")).config).toEqual(
  454. input.personalConfig,
  455. );
  456. expect(fixture.runtime.registryService.validateSelection(invalidSelection).ok).toBe(false);
  457. expect(fixture.runtime.registryService.validateSelection(selection).ok).toBe(true);
  458. expect(
  459. resolveInitialModelSelection({
  460. configuredDefault: await fixture.defaults.read(),
  461. registry: fixture.runtime.registryService.getView(),
  462. }),
  463. ).toEqual({ source: "registry-fallback", selection });
  464. expect(await fixture.defaults.read()).toEqual(invalidSelection);
  465. expect((await fixture.runtime.configService.read()).personalProviders.keys()).toEqual(
  466. expect.arrayContaining(["r3-store", "r3-broken"]),
  467. );
  468. });
  469. it("PRV-10 未知 schemaVersion / 损坏 provider 配置在任何写入前明确失败", async () => {
  470. const before = {
  471. personal: await readFile(fixture.personal, "utf8"),
  472. state: await readFile(fixture.state, "utf8"),
  473. settings: await fixture.settings.get(),
  474. };
  475. const unknownSchema = { ...envelope("unknown-schema", "x"), schemaVersion: 99 };
  476. await expect(
  477. fixture.target.apply(unknownSchema as unknown as ProviderProvisioningEnvelope),
  478. ).rejects.toThrow();
  479. const broken = envelope("broken-config", "x") as unknown as {
  480. personalConfig: { providerConfigRules: { providerRules: unknown[] } };
  481. };
  482. broken.personalConfig.providerConfigRules.providerRules = [
  483. { providerId: "r3-store", config: { group: "standard-personal", api: 42 } },
  484. ];
  485. await expect(
  486. fixture.target.apply(broken as unknown as ProviderProvisioningEnvelope),
  487. ).rejects.toThrow();
  488. expect(await readFile(fixture.personal, "utf8")).toBe(before.personal);
  489. expect(await readFile(fixture.state, "utf8")).toBe(before.state);
  490. expect(await fixture.settings.get()).toEqual(before.settings);
  491. expect(await fixture.credentials.load("oauth:zai:access_token")).toBe("old-value");
  492. expect(fixture.runtime.registryService.validateSelection(selection).ok).toBe(true);
  493. });
  494. it("PRV-02 Target 结果只会是 applied / already-applied / failed / rollback_failed 之一,失败不登记", async () => {
  495. vi.spyOn(fixture.account, "refresh").mockRejectedValueOnce(new Error("R3_FIRST_APPLY_FAULT"));
  496. const failed = await fixture.target.apply(envelope("first-apply-failed", "v2"));
  497. expect(failed).toMatchObject({ status: "failed", rolledBack: true });
  498. expect(await readFile(fixture.state, "utf8")).not.toContain("first-apply-failed");
  499. const retry = await fixture.target.apply(envelope("first-apply-failed", "v2"));
  500. expect(retry.status).toBe("applied");
  501. });
  502. });