config-update-preservation.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import fs from "node:fs";
  2. import os from "node:os";
  3. import { join } from "node:path";
  4. import yaml from "js-yaml";
  5. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. import {
  7. getConfigPath,
  8. resetConfig,
  9. setLegacyByokProviderMigrationEnabled,
  10. setManagedPresetBaseUrlSyncEnabled,
  11. } from "../src/config.js";
  12. import {
  13. compareAndSetLocalModelContext,
  14. updateLocalByokConfig,
  15. updateLocalModelSelection,
  16. } from "../src/local-model-provider-write.js";
  17. import {
  18. compareAndSetLocalModelContext as compareLegacyContext,
  19. updateLocalByokConfig as updateLegacyByok,
  20. updateLocalConfigFile,
  21. } from "../../local-runtime/src/config/update.js";
  22. const secret = "synthetic-config-preservation-key";
  23. const contextInput = {
  24. providerId: "minimax",
  25. modelId: "synthetic-model",
  26. expectedContextLimit: 100,
  27. contextLimit: 200,
  28. };
  29. const writers = [
  30. [
  31. "permission mode",
  32. () => updateLocalConfigFile({ field: "permissionMode", set: "default" }),
  33. ],
  34. [
  35. "prepared payload",
  36. () =>
  37. updateLocalConfigFile({}, new Set(["thinking"]), {
  38. thinking: { effort: "high" },
  39. }),
  40. ],
  41. [
  42. "legacy BYOK",
  43. () =>
  44. updateLegacyByok((draft) => {
  45. draft.minimax_api = { apiKey: secret };
  46. }),
  47. ],
  48. [
  49. "legacy model context",
  50. () => compareLegacyContext(contextInput, async () => true),
  51. ],
  52. [
  53. "model selection",
  54. () => updateLocalModelSelection({ modelKey: "minimax/synthetic-model" }),
  55. ],
  56. [
  57. "BYOK",
  58. () =>
  59. updateLocalByokConfig((draft) => {
  60. draft.minimax_api = { apiKey: secret };
  61. }),
  62. ],
  63. [
  64. "model context",
  65. () => compareAndSetLocalModelContext(contextInput, async () => true),
  66. ],
  67. ] as const;
  68. let root: string;
  69. let dataDir: string;
  70. let configPath: string;
  71. beforeEach(() => {
  72. root = fs.mkdtempSync(join(os.tmpdir(), "mcode-config-preservation-"));
  73. dataDir = join(root, "profile");
  74. fs.mkdirSync(dataDir);
  75. vi.spyOn(os, "homedir").mockReturnValue(root);
  76. vi.stubEnv("MINIMAX_DATA_DIR", dataDir);
  77. vi.stubEnv("__MAVIS_RUNTIME_MANAGED", "0");
  78. resetConfig();
  79. setLegacyByokProviderMigrationEnabled(false);
  80. setManagedPresetBaseUrlSyncEnabled(false);
  81. configPath = getConfigPath();
  82. });
  83. afterEach(() => {
  84. vi.restoreAllMocks();
  85. vi.unstubAllEnvs();
  86. resetConfig();
  87. setLegacyByokProviderMigrationEnabled(true);
  88. setManagedPresetBaseUrlSyncEnabled(true);
  89. fs.rmSync(root, { recursive: true, force: true });
  90. });
  91. describe.each(writers)("%s config updates", (_name, write) => {
  92. it.each([
  93. ["malformed YAML", `provider: [${secret}\n`],
  94. ["duplicate keys", `apiKey: ${secret}\napiKey: duplicate\n`],
  95. ["sequence", `- ${secret}\n`],
  96. ["scalar", `${secret}\n`],
  97. ["timestamp", "2026-01-01\n"],
  98. ])(
  99. "rejects %s without replacing the original file",
  100. async (_kind, source) => {
  101. fs.writeFileSync(configPath, source);
  102. const rename = vi.spyOn(fs.promises, "rename");
  103. await expect(write()).rejects.toThrow(/Invalid config\.yaml/);
  104. expect(fs.readFileSync(configPath, "utf8")).toBe(source);
  105. expect(rename).not.toHaveBeenCalled();
  106. expect(fs.readdirSync(dataDir)).toEqual(["config.yaml"]);
  107. },
  108. );
  109. it("does not expose configuration contents in parse errors", async () => {
  110. fs.writeFileSync(configPath, `provider: [${secret}\n`);
  111. const error = await write().catch((error: unknown) => error);
  112. expect(error).toBeInstanceOf(Error);
  113. expect(String(error)).not.toContain(secret);
  114. expect(error).not.toHaveProperty("cause");
  115. });
  116. it("aborts on a read failure and releases the lock", async () => {
  117. const source = `permissionMode: auto\n# ${secret}\n`;
  118. fs.writeFileSync(configPath, source);
  119. const read = vi.spyOn(fs, "readFileSync").mockImplementation(() => {
  120. throw Object.assign(new Error(`EACCES ${secret}`), { code: "EACCES" });
  121. });
  122. const rename = vi.spyOn(fs.promises, "rename");
  123. await expect(write()).rejects.toThrow(
  124. "Local runtime failed to update config file",
  125. );
  126. read.mockRestore();
  127. expect(fs.readFileSync(configPath, "utf8")).toBe(source);
  128. expect(rename).not.toHaveBeenCalled();
  129. expect(fs.readdirSync(dataDir)).toEqual(["config.yaml"]);
  130. });
  131. });
  132. describe("valid local config updates", () => {
  133. it.each([undefined, "", "# empty config\n", "{}\n", "null\n"])(
  134. "initializes a missing or empty document: %s",
  135. async (source) => {
  136. if (source !== undefined) fs.writeFileSync(configPath, source);
  137. await updateLocalConfigFile({ permissionMode: "default" });
  138. expect(yaml.load(fs.readFileSync(configPath, "utf8"))).toEqual({
  139. permissionMode: "default",
  140. });
  141. },
  142. );
  143. it("preserves unrelated settings and credentials", async () => {
  144. const source = {
  145. permissionMode: "auto",
  146. custom_provider: { example: { options: { apiKey: secret }, models: {} } },
  147. customSetting: { enabled: true },
  148. };
  149. fs.writeFileSync(configPath, yaml.dump(source));
  150. await updateLocalConfigFile({ field: "permissionMode", set: "default" });
  151. expect(yaml.load(fs.readFileSync(configPath, "utf8"))).toEqual({
  152. ...source,
  153. permissionMode: "default",
  154. });
  155. });
  156. it("can update the file after the user repairs malformed YAML", async () => {
  157. fs.writeFileSync(configPath, "provider: [");
  158. await expect(
  159. updateLocalConfigFile({ permissionMode: "default" }),
  160. ).rejects.toThrow();
  161. fs.writeFileSync(configPath, "permissionMode: auto\n");
  162. await updateLocalConfigFile({ permissionMode: "default" });
  163. expect(yaml.load(fs.readFileSync(configPath, "utf8"))).toEqual({
  164. permissionMode: "default",
  165. });
  166. });
  167. });