smoke.test.mjs 13 KB

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