byok.test.mjs 11 KB

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