smoke.test.mjs 13 KB

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