byok.test.mjs 16 KB

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