smoke.test.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import test from "node:test";
  2. import assert from "node:assert/strict";
  3. import { spawn, spawnSync } from "node:child_process";
  4. import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync, chmodSync, statSync } from "node:fs";
  5. import { tmpdir } from "node:os";
  6. import path from "node:path";
  7. import { fileURLToPath } from "node:url";
  8. import Database from "better-sqlite3";
  9. const root = fileURLToPath(new URL("../", import.meta.url));
  10. const cli = path.join(root, "dist/cli.js");
  11. // Full runtime startup can exceed 15s on Windows CI (ACP took 22s).
  12. // Match the ACP startup budget; lightweight help/validation stays at 15s.
  13. const runtimeTimeoutMs = process.platform === "win32" ? 30000 : 15000;
  14. function assertSuccessfulChild(result) {
  15. assert.equal(result.error, undefined,
  16. `CLI spawn failed: ${result.error?.message}; signal=${result.signal}; stderr=${result.stderr}`);
  17. assert.equal(result.status, 0, result.stderr);
  18. }
  19. const version = JSON.parse(
  20. readFileSync(path.join(root, "packages/tui/package.json"), "utf8"),
  21. ).version;
  22. function fixture(t, environment = process.env) {
  23. const dataDir = mkdtempSync(path.join(tmpdir(), "minimax-code-smoke-"));
  24. const audit = path.join(dataDir, "network-attempts.log");
  25. t.after(() => {
  26. try {
  27. assert.equal(
  28. existsSync(audit),
  29. false,
  30. existsSync(audit)
  31. ? readFileSync(audit, "utf8")
  32. : "Unexpected outbound network attempt",
  33. );
  34. } finally {
  35. rmSync(dataDir, { recursive: true, force: true });
  36. }
  37. });
  38. return {
  39. cwd: dataDir,
  40. env: {
  41. ...environment,
  42. // Proxy setup installs undici.fetch over the preloaded offline mock.
  43. // Keep host proxy settings out of these isolated test children.
  44. HTTP_PROXY: "",
  45. HTTPS_PROXY: "",
  46. ALL_PROXY: "",
  47. NO_PROXY: "",
  48. http_proxy: "",
  49. https_proxy: "",
  50. all_proxy: "",
  51. no_proxy: "",
  52. MINIMAX_DATA_DIR: dataDir,
  53. MAVIS_DATA_DIR: dataDir,
  54. MCODE_TEST_NETWORK_AUDIT: audit,
  55. MCODE_TEST_MANAGED_OFFLINE: "1",
  56. MCODE_TEST_PROCESS_PROBE: "1",
  57. NODE_OPTIONS: `--import=${new URL("./network-deny.mjs", import.meta.url).href}`,
  58. },
  59. };
  60. }
  61. test("CLI version and command help work outside the source directory", (t) => {
  62. const options = fixture(t);
  63. for (const [args, expected] of [
  64. [["--version"], version],
  65. [["--help"], "terminal coding agent"],
  66. [["exec", "--help"], "prompt"],
  67. ]) {
  68. const result = spawnSync(process.execPath, [cli, ...args], {
  69. ...options,
  70. encoding: "utf8",
  71. timeout: 15000,
  72. });
  73. assert.equal(result.status, 0, result.stderr);
  74. assert.ok(result.stdout.includes(expected), result.stdout);
  75. }
  76. });
  77. test("provider configuration loads from an isolated data directory", (t) => {
  78. const result = spawnSync(process.execPath, [cli, "provider", "list"], {
  79. ...fixture(t),
  80. encoding: "utf8",
  81. timeout: runtimeTimeoutMs,
  82. });
  83. assertSuccessfulChild(result);
  84. assert.match(result.stdout, /minimax/);
  85. assert.doesNotMatch(result.stdout, /custom_provider:/);
  86. });
  87. test("config permission failures preserve private reads and terminate unsafe startup", {
  88. skip: process.platform !== "darwin",
  89. }, (t) => {
  90. const options = fixture(t);
  91. const config = path.join(options.env.MINIMAX_DATA_DIR, "config.yaml");
  92. const backup = `${config}.bak.byok-legacy-provider.smoke`;
  93. const flag = (file, value) => {
  94. const result = spawnSync("chflags", [value, file], { encoding: "utf8" });
  95. assert.equal(result.status, 0, result.stderr);
  96. };
  97. const list = () => {
  98. const result = spawnSync(process.execPath, [cli, "provider", "list"], {
  99. ...options,
  100. encoding: "utf8",
  101. timeout: 15000,
  102. // A leaked startup watcher can handle SIGTERM without releasing the process.
  103. killSignal: "SIGKILL",
  104. });
  105. assert.equal(result.error, undefined, result.stderr);
  106. return result;
  107. };
  108. try {
  109. for (const file of [config, backup]) {
  110. writeFileSync(file, "logLevel: info\n", { mode: 0o400 });
  111. flag(file, "uchg");
  112. }
  113. const privateRead = list();
  114. assert.equal(privateRead.status, 0, privateRead.stderr);
  115. assert.doesNotMatch(privateRead.stderr, /Could not restrict legacy BYOK backup/);
  116. assert.equal(statSync(config).mode & 0o777, 0o400);
  117. assert.equal(statSync(backup).mode & 0o777, 0o400);
  118. flag(backup, "nouchg");
  119. chmodSync(backup, 0o644);
  120. flag(backup, "uchg");
  121. const backupWarning = list();
  122. assert.equal(backupWarning.status, 0, backupWarning.stderr);
  123. assert.match(backupWarning.stderr, /Could not restrict legacy BYOK backup/);
  124. assert.ok(backupWarning.stderr.includes(JSON.stringify(backup)));
  125. assert.equal(statSync(backup).mode & 0o777, 0o644);
  126. flag(config, "nouchg");
  127. chmodSync(config, 0o644);
  128. flag(config, "uchg");
  129. const unsafeRead = list();
  130. assert.equal(unsafeRead.status, 1, unsafeRead.stderr);
  131. assert.match(unsafeRead.stderr, /EPERM/);
  132. assert.equal(statSync(config).mode & 0o777, 0o644);
  133. } finally {
  134. for (const file of [config, backup]) {
  135. if (existsSync(file)) flag(file, "nouchg");
  136. }
  137. }
  138. });
  139. test("offline smoke children ignore ambient proxy variables", async (t) => {
  140. const proxyNames = [
  141. "HTTP_PROXY",
  142. "HTTPS_PROXY",
  143. "ALL_PROXY",
  144. "http_proxy",
  145. "https_proxy",
  146. "all_proxy",
  147. ];
  148. for (const name of proxyNames) {
  149. await t.test(name, (t) => {
  150. const environment = {
  151. ...process.env,
  152. ...Object.fromEntries(proxyNames.map((key) => [key, ""])),
  153. [name]: "http://127.0.0.1:9",
  154. };
  155. const options = fixture(t, environment);
  156. const result = spawnSync(process.execPath, [cli, "provider", "list"], {
  157. ...options,
  158. encoding: "utf8",
  159. timeout: runtimeTimeoutMs,
  160. });
  161. assertSuccessfulChild(result);
  162. assert.match(result.stdout, /minimax/);
  163. assert.match(
  164. readFileSync(options.env.MCODE_TEST_NETWORK_AUDIT + ".managed", "utf8"),
  165. /https:\/\/models\.dev\/api\.json|\/mavis\/api\/v1\/models-dev\/catalog/,
  166. );
  167. assert.equal(environment[name], "http://127.0.0.1:9");
  168. });
  169. }
  170. });
  171. test("native SQLite binding opens and reads a real database", () => {
  172. const db = new Database(":memory:");
  173. try {
  174. assert.equal(db.prepare("select 42 as value").get().value, 42);
  175. } finally {
  176. db.close();
  177. }
  178. });
  179. test(
  180. "ACP starts the real runtime and answers initialize over stdio",
  181. { timeout: 45000 },
  182. async (t) => {
  183. const child = spawn(process.execPath, [cli, "acp"], {
  184. ...fixture(t),
  185. stdio: ["pipe", "pipe", "pipe"],
  186. });
  187. t.after(() => {
  188. if (child.exitCode === null) child.kill("SIGTERM");
  189. });
  190. let stderr = "";
  191. child.stderr.on("data", (chunk) => {
  192. stderr += chunk;
  193. });
  194. const response = await new Promise((resolve, reject) => {
  195. let buffer = "";
  196. const timer = setTimeout(
  197. () => reject(new Error(`ACP initialize timed out: ${stderr}`)),
  198. 30000,
  199. );
  200. child.once("error", (error) => {
  201. clearTimeout(timer);
  202. reject(error);
  203. });
  204. child.once("exit", (code) => {
  205. clearTimeout(timer);
  206. reject(new Error(`ACP exited ${code}: ${stderr}`));
  207. });
  208. child.stdout.on("data", (chunk) => {
  209. buffer += chunk;
  210. while (buffer.includes("\n")) {
  211. const index = buffer.indexOf("\n");
  212. const line = buffer.slice(0, index);
  213. buffer = buffer.slice(index + 1);
  214. try {
  215. const message = JSON.parse(line);
  216. if (message.id === 1) {
  217. clearTimeout(timer);
  218. resolve(message);
  219. }
  220. } catch {
  221. reject(new Error(`Non-JSON ACP stdout: ${line}`));
  222. }
  223. }
  224. });
  225. child.stdin.write(
  226. JSON.stringify({
  227. jsonrpc: "2.0",
  228. id: 1,
  229. method: "initialize",
  230. params: {
  231. protocolVersion: 1,
  232. clientCapabilities: { _meta: { "terminal-auth": true } },
  233. clientInfo: { name: "minimax-code-smoke", version: "1" },
  234. },
  235. }) + "\n",
  236. );
  237. });
  238. assert.equal(response.error, undefined, JSON.stringify(response));
  239. assert.equal(response.result.protocolVersion, 1);
  240. assert.equal(response.result.authMethods[0].id, "minimax-code-login");
  241. assert.equal(response.result.agentInfo.version, version);
  242. child.stdin.end();
  243. await new Promise((resolve, reject) => {
  244. const timer = setTimeout(() => {
  245. child.kill("SIGTERM");
  246. reject(new Error("ACP did not shut down after EOF"));
  247. }, 10000);
  248. child.once("exit", (code) => {
  249. clearTimeout(timer);
  250. code === 0
  251. ? resolve()
  252. : reject(new Error(`ACP shutdown ${code}: ${stderr}`));
  253. });
  254. });
  255. },
  256. );
  257. test("internal environment overrides are rejected", (t) => {
  258. const options = fixture(t);
  259. for (const args of [
  260. ["--lane", "internal"],
  261. ["--env", "test"],
  262. ]) {
  263. const result = spawnSync(process.execPath, [cli, ...args], {
  264. ...options,
  265. encoding: "utf8",
  266. timeout: 15000,
  267. });
  268. assert.notEqual(
  269. result.status,
  270. 0,
  271. `${args.join(" ")} unexpectedly succeeded`,
  272. );
  273. assert.equal(result.error, undefined);
  274. }
  275. });
  276. test("local plugin browsing remains available with managed services offline", (t) => {
  277. const options = fixture(t);
  278. for (const args of [
  279. ["plugin", "list", "--marketplace", "local", "--json"],
  280. ["plugin", "list", "--available", "--marketplace", "local", "--json"],
  281. ]) {
  282. const result = spawnSync(process.execPath, [cli, ...args], {
  283. ...options,
  284. encoding: "utf8",
  285. timeout: runtimeTimeoutMs,
  286. });
  287. assertSuccessfulChild(result);
  288. const output = JSON.parse(result.stdout);
  289. assert.ok(output !== null);
  290. assert.doesNotMatch(result.stdout, /"official"/);
  291. }
  292. });
  293. test("managed commands remain discoverable without logging in", (t) => {
  294. for (const args of [["login", "--help"], ["logout", "--help"], ["update", "--help"], ["acp", "login", "--help"], ["provider", "use", "--help"]]) {
  295. const result = spawnSync(process.execPath, [cli, ...args], { ...fixture(t), encoding: "utf8", timeout: 15000 });
  296. assert.equal(result.status, 0, result.stderr);
  297. assert.match(result.stdout, /Usage:/);
  298. }
  299. });
  300. test("provider add validates token limits before opening the runtime", (t) => {
  301. const options = fixture(t);
  302. const args = [
  303. "provider", "add", "--name", "Invalid limits", "--base-url", "http://127.0.0.1:1/v1",
  304. "--model", "synthetic-model",
  305. ];
  306. for (const flag of ["--context-limit", "--output-limit"]) {
  307. for (const value of ["0", "-1", "1.5", "NaN", "Infinity", "9007199254740992"]) {
  308. const result = spawnSync(process.execPath, [cli, ...args, `${flag}=${value}`], {
  309. ...options, encoding: "utf8", timeout: 15000,
  310. });
  311. assert.equal(result.status, 1, result.stderr);
  312. assert.match(result.stderr, /positive safe integer/);
  313. assert.ok(result.stderr.includes(flag), result.stderr);
  314. }
  315. }
  316. assert.equal(existsSync(path.join(options.cwd, "config.yaml")), false);
  317. });