byok.test.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. import test from "node:test";
  2. import assert from "node:assert/strict";
  3. import { createServer } from "node:http";
  4. import { spawn } from "node:child_process";
  5. import {
  6. mkdtempSync,
  7. mkdirSync,
  8. rmSync,
  9. existsSync,
  10. readFileSync,
  11. writeFileSync,
  12. } from "node:fs";
  13. import { tmpdir } from "node:os";
  14. import path from "node:path";
  15. import { fileURLToPath } from "node:url";
  16. import Database from "better-sqlite3";
  17. import { parse as parseYaml } from "yaml";
  18. const cli = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
  19. // This fixture validates BYOK transport and real Runtime persistence, not model quality.
  20. test(
  21. "BYOK runs without managed login and resumes its saved conversation",
  22. { timeout: 90000 },
  23. async (t) => {
  24. const dataDir = mkdtempSync(path.join(tmpdir(), "minimax-code-byok-"));
  25. const dbPath = path.join(dataDir, "v2", "sqlite", "runtime-state.sqlite");
  26. mkdirSync(path.dirname(dbPath), { recursive: true });
  27. const legacyDb = new Database(dbPath);
  28. try {
  29. // An upgrade must ignore a previously enabled cloud-indexing preference.
  30. legacyDb.exec(`
  31. CREATE TABLE local_runtime_preferences (key TEXT PRIMARY KEY, value_json TEXT NOT NULL);
  32. INSERT INTO local_runtime_preferences VALUES ('workspace-indexing-enabled', 'true');
  33. `);
  34. } finally {
  35. legacyDb.close();
  36. }
  37. const requests = [];
  38. const readMarker = `ACTUAL_FILE_CONTENT_${Date.now()}`;
  39. writeFileSync(path.join(dataDir, "read-fixture.txt"), readMarker);
  40. let toolRequested = false;
  41. let rejectConnection = false;
  42. const networkAudit = path.join(dataDir, "network-audit.log");
  43. const server = createServer(async (req, res) => {
  44. let raw = "";
  45. for await (const chunk of req) raw += chunk;
  46. const body = JSON.parse(raw);
  47. requests.push({ url: req.url, auth: req.headers.authorization, body });
  48. if (!req.url?.endsWith("/chat/completions")) {
  49. res.writeHead(404).end();
  50. return;
  51. }
  52. if (rejectConnection) {
  53. res.writeHead(401, { "content-type": "application/json" }).end(
  54. JSON.stringify({ error: { message: "Synthetic invalid credential" } }),
  55. );
  56. return;
  57. }
  58. if (!body.stream) {
  59. res.writeHead(200, { "content-type": "application/json" }).end(
  60. JSON.stringify({
  61. id: "fixture",
  62. object: "chat.completion",
  63. model: "fixture-model",
  64. choices: [
  65. {
  66. index: 0,
  67. message: { role: "assistant", content: "LOCAL_BYOK_OK" },
  68. finish_reason: "stop",
  69. },
  70. ],
  71. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  72. }),
  73. );
  74. return;
  75. }
  76. res.writeHead(200, { "content-type": "text/event-stream" });
  77. if (
  78. JSON.stringify(body.messages).includes("TOOL_READ_TEST") &&
  79. !toolRequested
  80. ) {
  81. toolRequested = true;
  82. assert.ok(body.tools?.some((tool) => tool.function?.name === "read"));
  83. for (const delta of [
  84. {
  85. choices: [
  86. {
  87. index: 0,
  88. delta: {
  89. role: "assistant",
  90. tool_calls: [
  91. {
  92. index: 0,
  93. id: "read-fixture-call",
  94. type: "function",
  95. function: {
  96. name: "read",
  97. arguments: JSON.stringify({
  98. path: path.join(dataDir, "read-fixture.txt"),
  99. }),
  100. },
  101. },
  102. ],
  103. },
  104. finish_reason: null,
  105. },
  106. ],
  107. },
  108. { choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] },
  109. ])
  110. res.write(
  111. `data: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", created: 1, model: "fixture-model", ...delta })}\n\n`,
  112. );
  113. res.end("data: [DONE]\n\n");
  114. return;
  115. }
  116. for (const chunk of [
  117. {
  118. choices: [
  119. {
  120. index: 0,
  121. delta: { role: "assistant", content: "LOCAL_BYOK_OK" },
  122. finish_reason: null,
  123. },
  124. ],
  125. },
  126. {
  127. choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
  128. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  129. },
  130. ])
  131. res.write(
  132. `data: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", created: 1, model: "fixture-model", ...chunk })}\n\n`,
  133. );
  134. res.end("data: [DONE]\n\n");
  135. });
  136. await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  137. t.after(async () => {
  138. server.closeAllConnections();
  139. await new Promise((resolve) => server.close(resolve));
  140. try {
  141. assert.equal(
  142. existsSync(networkAudit),
  143. false,
  144. existsSync(networkAudit)
  145. ? readFileSync(networkAudit, "utf8")
  146. : "Unexpected external request",
  147. );
  148. } finally {
  149. rmSync(dataDir, { recursive: true, force: true });
  150. }
  151. });
  152. const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;
  153. const env = {
  154. ...process.env,
  155. MINIMAX_DATA_DIR: dataDir,
  156. MAVIS_DATA_DIR: dataDir,
  157. MCODE_PROVIDER_API_KEY: "fixture-only-key",
  158. MCODE_TEST_ALLOWED_ORIGIN: new URL(baseUrl).origin,
  159. MCODE_TEST_NETWORK_AUDIT: networkAudit,
  160. MCODE_TEST_MANAGED_OFFLINE: "1",
  161. MCODE_TEST_PROCESS_PROBE: "1",
  162. NODE_OPTIONS: `--import=${new URL("./network-deny.mjs", import.meta.url).href}`,
  163. HTTP_PROXY: "",
  164. HTTPS_PROXY: "",
  165. ALL_PROXY: "",
  166. };
  167. let commandSequence = 0;
  168. async function run(args) {
  169. const startedAt = Date.now();
  170. const label = args.slice(0, 2).join(" ");
  171. const requestCountAtStart = requests.length;
  172. const diagnosticsDir = path.join(dataDir, `cli-diagnostics-${++commandSequence}`);
  173. const commandArgs = args[0] === "exec"
  174. ? [...args, "--diagnostics-dir", diagnosticsDir]
  175. : args;
  176. return new Promise((resolve, reject) => {
  177. const child = spawn(process.execPath, [cli, ...commandArgs], {
  178. cwd: dataDir,
  179. env,
  180. stdio: ["ignore", "pipe", "pipe"],
  181. });
  182. let stdout = "",
  183. stderr = "";
  184. let timeoutError;
  185. const timer = setTimeout(() => {
  186. const progressPath = path.join(diagnosticsDir, "progress.jsonl");
  187. let progress = "No execution progress recorded";
  188. try {
  189. if (existsSync(progressPath))
  190. progress = readFileSync(progressPath, "utf8").slice(-12000);
  191. } catch (error) {
  192. progress = `Unable to read execution progress: ${error.message}`;
  193. }
  194. timeoutError = new Error(
  195. `Timed out after ${Date.now() - startedAt}ms: ${label}\n` +
  196. `Fixture requests during command: ${requests.length - requestCountAtStart}\n` +
  197. `stdout (tail): ${stdout.slice(-12000)}\nstderr (tail): ${stderr.slice(-12000)}\n` +
  198. `execution progress (tail): ${progress}`,
  199. );
  200. child.kill("SIGKILL");
  201. child.stdout.destroy();
  202. child.stderr.destroy();
  203. }, 35000);
  204. child.stdout.on("data", (chunk) => {
  205. stdout += chunk;
  206. });
  207. child.stderr.on("data", (chunk) => {
  208. stderr += chunk;
  209. });
  210. child.once("error", (error) => {
  211. clearTimeout(timer);
  212. reject(error);
  213. });
  214. child.once("close", (code) => {
  215. clearTimeout(timer);
  216. t.diagnostic(`${label}: exit ${code} after ${Date.now() - startedAt}ms`);
  217. if (timeoutError) {
  218. reject(timeoutError);
  219. return;
  220. }
  221. code === 0
  222. ? resolve(stdout)
  223. : reject(new Error(`CLI exited ${code}: ${stderr}\n${stdout}`));
  224. });
  225. });
  226. }
  227. await run([
  228. "provider",
  229. "add",
  230. "--name",
  231. "Fixture",
  232. "--base-url",
  233. baseUrl,
  234. "--api-format",
  235. "openai-completions",
  236. "--model",
  237. "fixture-model",
  238. ]);
  239. assert.equal(requests.length, 0, "Adding without --use must not test or activate");
  240. const snapshot = JSON.parse(await run(["provider", "list", "--json"]));
  241. assert.equal(
  242. snapshot.providers.some((p) => p.kind === "minimax-oauth"),
  243. true,
  244. );
  245. const selected = snapshot.providers.find(
  246. (p) => p.kind === "custom" && p.name === "Fixture",
  247. );
  248. assert.ok(selected?.hasApiKey);
  249. await run([
  250. "provider",
  251. "test",
  252. selected.providerId,
  253. "--model",
  254. "fixture-model",
  255. ]);
  256. const configPath = path.join(dataDir, "config.yaml");
  257. const savedConfig = () => parseYaml(readFileSync(configPath, "utf8"));
  258. assert.equal(savedConfig().defaultModel, "minimax/MiniMax-M3");
  259. assert.equal(savedConfig().custom_provider.fixture.models["fixture-model"].limit, undefined);
  260. assert.equal(selected.active, false);
  261. assert.equal(selected.models[0].contextLimit, undefined);
  262. assert.equal(selected.models[0].maxOutputTokens, undefined);
  263. const addArgs = [
  264. "provider", "add", "--name", "Limited", "--base-url", baseUrl,
  265. "--api-format", "openai-completions", "--model", "fixture-model",
  266. "--model", "second-model", "--context-limit", "32768", "--output-limit", "4096", "--use",
  267. ];
  268. const beforeFailure = readFileSync(configPath, "utf8");
  269. rejectConnection = true;
  270. await assert.rejects(run(addArgs), /Provider connection test failed.*Nothing was saved/s);
  271. assert.equal(readFileSync(configPath, "utf8"), beforeFailure);
  272. rejectConnection = false;
  273. const beforeAdd = requests.length;
  274. assert.match(await run(addArgs), /Provider added and selected: Limited/);
  275. assert.ok(requests.length > beforeAdd, "Activation must test the candidate before saving");
  276. assert.equal(requests[beforeAdd].body.model, "fixture-model");
  277. const config = savedConfig();
  278. assert.equal(config.defaultModel, "custom_provider:limited/fixture-model");
  279. for (const model of ["fixture-model", "second-model"]) {
  280. assert.deepEqual(config.custom_provider.limited.models[model].limit, { context: 32768, output: 4096 });
  281. }
  282. const configured = JSON.parse(await run(["provider", "list", "--json"])).providers.find(
  283. (provider) => provider.name === "Limited",
  284. );
  285. assert.equal(configured.active, true);
  286. assert.equal(configured.models[0].selected, true);
  287. for (const model of configured.models) {
  288. assert.equal(model.contextLimit, 32768);
  289. assert.equal(model.maxOutputTokens, 4096);
  290. }
  291. const beforeSaveOnly = requests.length;
  292. for (const [name, flag, limit] of [
  293. ["context-only", "--context-limit", { context: 32768 }],
  294. ["output-only", "--output-limit", { output: 32768 }],
  295. ]) {
  296. await run([
  297. "provider", "add", "--name", name, "--base-url", baseUrl,
  298. "--api-format", "openai-completions", "--model", "fixture-model", flag, "32768",
  299. ]);
  300. assert.deepEqual(savedConfig().custom_provider[name].models["fixture-model"].limit, limit);
  301. assert.equal(savedConfig().defaultModel, config.defaultModel);
  302. }
  303. assert.equal(requests.length, beforeSaveOnly, "Limits alone must not test or select a model");
  304. const modelArgs = ["--model", `${selected.providerId}/fixture-model`];
  305. // The first run must work through the saved default, without --model or managed login.
  306. const first = await run([
  307. "exec",
  308. "Remember this marker: SOURCE_REPOSITORY_TEST",
  309. "--timeout",
  310. "20s",
  311. "--max-steps",
  312. "1",
  313. ]);
  314. assert.match(first, /LOCAL_BYOK_OK/);
  315. await assert.rejects(run([
  316. 'exec', 'Managed model still requires its own login',
  317. '--model', 'minimax/MiniMax-M3', '--timeout', '20s', '--max-steps', '1',
  318. ]), /Sign in to MiniMax/);
  319. const beforeResume = requests.length;
  320. const second = await run([
  321. "exec",
  322. "Repeat the marker",
  323. ...modelArgs,
  324. "--continue",
  325. "--timeout",
  326. "20s",
  327. "--max-steps",
  328. "1",
  329. ]);
  330. assert.match(second, /LOCAL_BYOK_OK/);
  331. assert.ok(
  332. requests
  333. .slice(beforeResume)
  334. .some((r) =>
  335. JSON.stringify(r.body.messages ?? []).includes(
  336. "SOURCE_REPOSITORY_TEST",
  337. ),
  338. ),
  339. JSON.stringify(
  340. requests.map((r) => ({ url: r.url, keys: Object.keys(r.body) })),
  341. ),
  342. );
  343. const toolStart = requests.length;
  344. await run([
  345. "exec",
  346. "TOOL_READ_TEST: read read-fixture.txt",
  347. ...modelArgs,
  348. "--timeout",
  349. "20s",
  350. "--max-steps",
  351. "3",
  352. ]);
  353. assert.equal(toolRequested, true);
  354. assert.ok(
  355. requests
  356. .slice(toolStart)
  357. .some((r) =>
  358. r.body.messages?.some(
  359. (m) =>
  360. m.role === "tool" &&
  361. JSON.stringify(m.content).includes(readMarker),
  362. ),
  363. ),
  364. "The real read tool must return file contents to the provider",
  365. );
  366. assert.ok(requests.length >= 2);
  367. assert.ok(requests.every((r) => r.auth === "Bearer fixture-only-key"));
  368. assert.equal(
  369. requests.some((r) => r.body.tools?.some(
  370. (tool) => tool.function?.name === "workspace_semantic_search",
  371. )),
  372. false,
  373. "The retired workspace search tool must not be exposed to the model",
  374. );
  375. assert.equal(
  376. existsSync(path.join(dataDir, "v2", "workspaces")),
  377. false,
  378. "Startup, completed turns and resume must not create indexing artifacts",
  379. );
  380. const managedAudit = `${networkAudit}.managed`;
  381. assert.doesNotMatch(
  382. existsSync(managedAudit) ? readFileSync(managedAudit, "utf8") : "",
  383. /workspace-indexing/,
  384. "No workspace indexing request may be attempted",
  385. );
  386. const verificationDb = new Database(dbPath, { readonly: true });
  387. try {
  388. assert.deepEqual(
  389. verificationDb.prepare(
  390. "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'local_runtime_workspace_indexing_%'",
  391. ).all(),
  392. [],
  393. "New runtime databases must not create the retired upload queue",
  394. );
  395. } finally {
  396. verificationDb.close();
  397. }
  398. },
  399. );