smoke.test.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 { withoutProxyEnvironment } from "./offline-environment.mjs";
  10. const root = fileURLToPath(new URL("../", import.meta.url));
  11. const cli = path.join(root, "dist/cli.js");
  12. // Full runtime startup can exceed 15s on Windows CI (ACP took 22s).
  13. // Match the ACP startup budget; lightweight help/validation stays at 15s.
  14. const runtimeTimeoutMs = process.platform === "win32" ? 30000 : 15000;
  15. function assertSuccessfulChild(result) {
  16. assert.equal(result.error, undefined,
  17. `CLI spawn failed: ${result.error?.message}; signal=${result.signal}; stderr=${result.stderr}`);
  18. assert.equal(result.status, 0, result.stderr);
  19. }
  20. const version = JSON.parse(
  21. readFileSync(path.join(root, "packages/tui/package.json"), "utf8"),
  22. ).version;
  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. "http_proxy",
  166. "https_proxy",
  167. "all_proxy",
  168. ];
  169. for (const name of proxyNames) {
  170. await t.test(name, (t) => {
  171. const environment = {
  172. ...process.env,
  173. ...Object.fromEntries(proxyNames.map((key) => [key, ""])),
  174. [name]: "http://127.0.0.1:9",
  175. };
  176. const options = fixture(t, environment);
  177. const result = spawnSync(process.execPath, [cli, "provider", "list"], {
  178. ...options,
  179. encoding: "utf8",
  180. timeout: runtimeTimeoutMs,
  181. });
  182. assertSuccessfulChild(result);
  183. assert.match(result.stdout, /minimax/);
  184. assert.match(
  185. readFileSync(options.env.MCODE_TEST_NETWORK_AUDIT + ".managed", "utf8"),
  186. /https:\/\/models\.dev\/api\.json|\/mavis\/api\/v1\/models-dev\/catalog/,
  187. );
  188. assert.equal(environment[name], "http://127.0.0.1:9");
  189. });
  190. }
  191. });
  192. test("native SQLite binding opens and reads a real database", () => {
  193. const db = new Database(":memory:");
  194. try {
  195. assert.equal(db.prepare("select 42 as value").get().value, 42);
  196. } finally {
  197. db.close();
  198. }
  199. });
  200. test(
  201. "ACP starts the real runtime and answers initialize over stdio",
  202. { timeout: 45000 },
  203. async (t) => {
  204. const child = spawn(process.execPath, [cli, "acp"], {
  205. ...fixture(t),
  206. stdio: ["pipe", "pipe", "pipe"],
  207. });
  208. t.after(() => {
  209. if (child.exitCode === null) child.kill("SIGTERM");
  210. });
  211. let stderr = "";
  212. child.stderr.on("data", (chunk) => {
  213. stderr += chunk;
  214. });
  215. const response = await new Promise((resolve, reject) => {
  216. let buffer = "";
  217. const timer = setTimeout(
  218. () => reject(new Error(`ACP initialize timed out: ${stderr}`)),
  219. 30000,
  220. );
  221. child.once("error", (error) => {
  222. clearTimeout(timer);
  223. reject(error);
  224. });
  225. child.once("exit", (code) => {
  226. clearTimeout(timer);
  227. reject(new Error(`ACP exited ${code}: ${stderr}`));
  228. });
  229. child.stdout.on("data", (chunk) => {
  230. buffer += chunk;
  231. while (buffer.includes("\n")) {
  232. const index = buffer.indexOf("\n");
  233. const line = buffer.slice(0, index);
  234. buffer = buffer.slice(index + 1);
  235. try {
  236. const message = JSON.parse(line);
  237. if (message.id === 1) {
  238. clearTimeout(timer);
  239. resolve(message);
  240. }
  241. } catch {
  242. reject(new Error(`Non-JSON ACP stdout: ${line}`));
  243. }
  244. }
  245. });
  246. child.stdin.write(
  247. JSON.stringify({
  248. jsonrpc: "2.0",
  249. id: 1,
  250. method: "initialize",
  251. params: {
  252. protocolVersion: 1,
  253. clientCapabilities: { _meta: { "terminal-auth": true } },
  254. clientInfo: { name: "minimax-code-smoke", version: "1" },
  255. },
  256. }) + "\n",
  257. );
  258. });
  259. assert.equal(response.error, undefined, JSON.stringify(response));
  260. assert.equal(response.result.protocolVersion, 1);
  261. assert.equal(response.result.authMethods[0].id, "minimax-code-login");
  262. assert.equal(response.result.agentInfo.version, version);
  263. child.stdin.end();
  264. await new Promise((resolve, reject) => {
  265. const timer = setTimeout(() => {
  266. child.kill("SIGTERM");
  267. reject(new Error("ACP did not shut down after EOF"));
  268. }, 10000);
  269. child.once("exit", (code) => {
  270. clearTimeout(timer);
  271. code === 0
  272. ? resolve()
  273. : reject(new Error(`ACP shutdown ${code}: ${stderr}`));
  274. });
  275. });
  276. },
  277. );
  278. test("internal environment overrides are rejected", (t) => {
  279. const options = fixture(t);
  280. for (const args of [
  281. ["--lane", "internal"],
  282. ["--env", "test"],
  283. ]) {
  284. const result = spawnSync(process.execPath, [cli, ...args], {
  285. ...options,
  286. encoding: "utf8",
  287. timeout: 15000,
  288. });
  289. assert.notEqual(
  290. result.status,
  291. 0,
  292. `${args.join(" ")} unexpectedly succeeded`,
  293. );
  294. assert.equal(result.error, undefined);
  295. }
  296. });
  297. test("local plugin browsing remains available with managed services offline", (t) => {
  298. const options = fixture(t);
  299. for (const args of [
  300. ["plugin", "list", "--marketplace", "local", "--json"],
  301. ["plugin", "list", "--available", "--marketplace", "local", "--json"],
  302. ]) {
  303. const result = spawnSync(process.execPath, [cli, ...args], {
  304. ...options,
  305. encoding: "utf8",
  306. timeout: runtimeTimeoutMs,
  307. });
  308. assertSuccessfulChild(result);
  309. const output = JSON.parse(result.stdout);
  310. assert.ok(output !== null);
  311. assert.doesNotMatch(result.stdout, /"official"/);
  312. }
  313. });
  314. test("managed commands remain discoverable without logging in", (t) => {
  315. for (const args of [["login", "--help"], ["logout", "--help"], ["update", "--help"], ["acp", "login", "--help"], ["provider", "use", "--help"]]) {
  316. const result = spawnSync(process.execPath, [cli, ...args], { ...fixture(t), encoding: "utf8", timeout: 15000 });
  317. assert.equal(result.status, 0, result.stderr);
  318. assert.match(result.stdout, /Usage:/);
  319. }
  320. });
  321. test("provider add validates token limits before opening the runtime", (t) => {
  322. const options = fixture(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 flag of ["--context-limit", "--output-limit"]) {
  328. for (const value of ["0", "-1", "1.5", "NaN", "Infinity", "9007199254740992"]) {
  329. const result = spawnSync(process.execPath, [cli, ...args, `${flag}=${value}`], {
  330. ...options, encoding: "utf8", timeout: 15000,
  331. });
  332. assert.equal(result.status, 1, result.stderr);
  333. assert.match(result.stderr, /positive safe integer/);
  334. assert.ok(result.stderr.includes(flag), result.stderr);
  335. }
  336. }
  337. assert.equal(existsSync(path.join(options.cwd, "config.yaml")), false);
  338. });