Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(cli): R5 — test --latency/--repeat/--compare/--save (spec 8.7 test-provider)

diegosouzapwdcc21f105239
diff --git a/bin/cli/commands/test-provider.mjs b/bin/cli/commands/test-provider.mjs
index d398fa6a23..885251dd69 100644
--- a/bin/cli/commands/test-provider.mjs
+++ b/bin/cli/commands/test-provider.mjs
@@ -1,3 +1,4 @@
+import { writeFileSync } from "node:fs";
import { apiFetch, isServerUp } from "../api.mjs";
import { t } from "../i18n.mjs";
@@ -5,8 +6,12 @@ export function registerTestProvider(program) {
program
.command("test [provider] [model]")
.description(t("test.description"))
- .option("--all-providers", "Test all configured providers")
- .option("--json", "Output as JSON")
+ .option("--all-providers", t("test.allProvidersOpt"))
+ .option("--json", t("common.jsonOpt"))
+ .option("--latency", t("test.latencyOpt"))
+ .option("--repeat <n>", t("test.repeatOpt"), parseInt)
+ .option("--compare <models>", t("test.compareOpt"))
+ .option("--save <path>", t("test.saveOpt"))
.action(async (provider, model, opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const exitCode = await runTestProviderCommand(provider, model, {
@@ -24,39 +29,157 @@ export async function runTestProviderCommand(provider, model, opts = {}) {
return 1;
}
+ if (opts.compare) {
+ return _runCompare(provider, opts);
+ }
+
const targetProvider = provider || "anthropic";
const targetModel = model || "claude-haiku-4-5-20251001";
+ const repeat = opts.repeat && opts.repeat > 0 ? opts.repeat : 1;
+
+ const results = [];
+ for (let i = 0; i < repeat; i++) {
+ const result = await _runSingleTest(targetProvider, targetModel);
+ results.push(result);
+ }
+
+ const aggregated = _aggregate(results, opts.latency);
+
+ if (opts.save) {
+ try {
+ writeFileSync(opts.save, JSON.stringify(aggregated, null, 2), "utf8");
+ console.log(t("test.saved", { path: opts.save }));
+ } catch (err) {
+ console.error(
+ t("common.error", { message: err instanceof Error ? err.message : String(err) })
+ );
+ }
+ }
+
+ if (opts.json || opts.output === "json") {
+ console.log(JSON.stringify(aggregated, null, 2));
+ return aggregated.success ? 0 : 1;
+ }
+
+ _printResult(aggregated, opts.latency);
+ return aggregated.success ? 0 : 1;
+}
+
+async function _runCompare(provider, opts) {
+ const targetProvider = provider || "anthropic";
+ const models = opts.compare
+ .split(",")
+ .map((m) => m.trim())
+ .filter(Boolean);
+ if (models.length < 2) {
+ console.error(t("test.compareMinTwo"));
+ return 1;
+ }
+
+ const repeat = opts.repeat && opts.repeat > 0 ? opts.repeat : 1;
+ const rows = [];
- console.log(t("test.testing", { provider: targetProvider, model: targetModel }));
+ for (const model of models) {
+ const results = [];
+ for (let i = 0; i < repeat; i++) {
+ const result = await _runSingleTest(targetProvider, model);
+ results.push(result);
+ }
+ rows.push({ model, ..._aggregate(results, true) });
+ }
+
+ if (opts.save) {
+ try {
+ writeFileSync(opts.save, JSON.stringify(rows, null, 2), "utf8");
+ console.log(t("test.saved", { path: opts.save }));
+ } catch (err) {
+ console.error(
+ t("common.error", { message: err instanceof Error ? err.message : String(err) })
+ );
+ }
+ }
+ if (opts.json || opts.output === "json") {
+ console.log(JSON.stringify(rows, null, 2));
+ return rows.every((r) => r.success) ? 0 : 1;
+ }
+
+ console.log(`\n\x1b[1m\x1b[36m${t("test.compareTitle")}\x1b[0m\n`);
+ const colW = Math.max(...models.map((m) => m.length), 20);
+ console.log(
+ ` ${"Model".padEnd(colW)} ${"Status".padEnd(8)} ${"Avg ms".padEnd(8)} ${"Min ms".padEnd(8)} Max ms`
+ );
+ console.log(` ${"─".repeat(colW)} ──────── ──────── ──────── ──────`);
+ for (const row of rows) {
+ const statusMark = row.success ? "\x1b[32m✔\x1b[0m" : "\x1b[31m✖\x1b[0m";
+ const avg = row.latency?.avgMs != null ? String(row.latency.avgMs) : "N/A";
+ const min = row.latency?.minMs != null ? String(row.latency.minMs) : "N/A";
+ const max = row.latency?.maxMs != null ? String(row.latency.maxMs) : "N/A";
+ console.log(
+ ` ${row.model.padEnd(colW)} ${statusMark} ${avg.padEnd(8)} ${min.padEnd(8)} ${max}`
+ );
+ }
+ console.log();
+
+ return rows.every((r) => r.success) ? 0 : 1;
+}
+
+async function _runSingleTest(provider, model) {
+ const startMs = Date.now();
try {
const res = await apiFetch("/api/v1/providers/test", {
method: "POST",
- body: { provider: targetProvider, model: targetModel },
+ body: { provider, model },
retry: false,
timeout: 30000,
acceptNotOk: true,
});
+ const durationMs = Date.now() - startMs;
+ const data = res.ok ? await res.json() : { success: false, error: `HTTP ${res.status}` };
+ return { ...data, durationMs };
+ } catch (err) {
+ return {
+ success: false,
+ error: err instanceof Error ? err.message : String(err),
+ durationMs: Date.now() - startMs,
+ };
+ }
+}
- const result = res.ok ? await res.json() : { success: false, error: `HTTP ${res.status}` };
-
- if (opts.json || opts.output === "json") {
- console.log(JSON.stringify(result, null, 2));
- return result.success ? 0 : 1;
- }
-
- if (result.success) {
- console.log(`\x1b[32m✔ ${t("test.passed")}\x1b[0m`);
- if (result.response) console.log(`\x1b[2m Response: ${result.response}\x1b[0m`);
- return 0;
- }
+function _aggregate(results, includeLatency) {
+ const allOk = results.every((r) => r.success);
+ const durations = results.map((r) => r.durationMs).filter((d) => d != null);
+ const base = {
+ success: allOk,
+ runs: results.length,
+ passed: results.filter((r) => r.success).length,
+ failed: results.filter((r) => !r.success).length,
+ response: results.find((r) => r.response)?.response,
+ error: results.find((r) => r.error)?.error,
+ };
+ if (includeLatency && durations.length > 0) {
+ const avgMs = Math.round(durations.reduce((a, b) => a + b, 0) / durations.length);
+ const minMs = Math.min(...durations);
+ const maxMs = Math.max(...durations);
+ return { ...base, latency: { avgMs, minMs, maxMs } };
+ }
+ return base;
+}
+function _printResult(result, showLatency) {
+ if (result.success) {
+ const runs = result.runs > 1 ? ` (${result.passed}/${result.runs} passed)` : "";
+ console.log(`\x1b[32m✔ ${t("test.passed")}\x1b[0m${runs}`);
+ if (result.response) console.log(`\x1b[2m Response: ${result.response}\x1b[0m`);
+ } else {
+ const runs = result.runs > 1 ? ` (${result.passed}/${result.runs} passed)` : "";
console.error(
- `\x1b[31m✖ ${t("test.failed", { error: result.error || "Unknown error" })}\x1b[0m`
+ `\x1b[31m✖ ${t("test.failed", { error: result.error || "Unknown error" })}\x1b[0m${runs}`
+ );
+ }
+ if (showLatency && result.latency) {
+ console.log(
+ `\x1b[2m Latency — avg: ${result.latency.avgMs}ms min: ${result.latency.minMs}ms max: ${result.latency.maxMs}ms\x1b[0m`
);
- return 1;
- } catch (err) {
- console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
- return 1;
}
}
diff --git a/bin/cli/locales/en.json b/bin/cli/locales/en.json
index bdde565617..5ba762584b 100644
--- a/bin/cli/locales/en.json
+++ b/bin/cli/locales/en.json
@@ -282,7 +282,15 @@
"noServer": "Server not running. Start with: omniroute serve",
"testing": "Testing {provider} / {model}...",
"passed": "Connection successful!",
- "failed": "Connection failed: {error}"
+ "failed": "Connection failed: {error}",
+ "allProvidersOpt": "Test all configured providers",
+ "latencyOpt": "Show latency measurements (avg/min/max ms)",
+ "repeatOpt": "Repeat test N times and aggregate results",
+ "compareOpt": "Comma-separated models to compare (e.g. gpt-4o,claude-3-5-sonnet)",
+ "saveOpt": "Save results to a JSON file",
+ "saved": "Results saved to {path}",
+ "compareTitle": "Model Comparison",
+ "compareMinTwo": "At least two models required for --compare (comma-separated)"
},
"update": {
"checking": "Checking for updates...",
diff --git a/bin/cli/locales/pt-BR.json b/bin/cli/locales/pt-BR.json
index 6843e5651f..a157f112f2 100644
--- a/bin/cli/locales/pt-BR.json
+++ b/bin/cli/locales/pt-BR.json
@@ -282,7 +282,15 @@
"noServer": "Servidor não está em execução. Inicie com: omniroute serve",
"testing": "Testando {provider} / {model}...",
"passed": "Conexão bem-sucedida!",
- "failed": "Conexão falhou: {error}"
+ "failed": "Conexão falhou: {error}",
+ "allProvidersOpt": "Testar todos os provedores configurados",
+ "latencyOpt": "Exibir medições de latência (avg/min/max ms)",
+ "repeatOpt": "Repetir o teste N vezes e agregar os resultados",
+ "compareOpt": "Modelos separados por vírgula para comparar (ex: gpt-4o,claude-3-5-sonnet)",
+ "saveOpt": "Salvar resultados em arquivo JSON",
+ "saved": "Resultados salvos em {path}",
+ "compareTitle": "Comparação de Modelos",
+ "compareMinTwo": "São necessários pelo menos dois modelos para --compare (separados por vírgula)"
},
"update": {
"checking": "Verificando atualizações...",
diff --git a/tests/unit/cli-expanded-commands.test.ts b/tests/unit/cli-expanded-commands.test.ts
index 589770fbc2..3e8aafd379 100644
--- a/tests/unit/cli-expanded-commands.test.ts
+++ b/tests/unit/cli-expanded-commands.test.ts
@@ -113,3 +113,36 @@ test("update --check com versão atual não lança", async () => {
}
assert.ok(code === 0 || code === 1);
});
+
+test("test-provider.mjs exporta runTestProviderCommand com novas flags", async () => {
+ const mod = await import("../../bin/cli/commands/test-provider.mjs");
+ assert.equal(typeof mod.registerTestProvider, "function");
+ assert.equal(typeof mod.runTestProviderCommand, "function");
+});
+
+test("test-provider — registerTestProvider registra flags latency/repeat/compare/save", async () => {
+ const { registerTestProvider } = await import("../../bin/cli/commands/test-provider.mjs");
+ const { Command } = await import("commander");
+ const prog = new Command().exitOverride();
+ registerTestProvider(prog);
+ const testCmd = prog.commands.find((c) => c.name() === "test");
+ assert.ok(testCmd, "test command deve existir");
+ const optNames = testCmd.options.map((o: any) => o.long);
+ assert.ok(optNames.includes("--latency"), "--latency deve existir");
+ assert.ok(optNames.includes("--repeat"), "--repeat deve existir");
+ assert.ok(optNames.includes("--compare"), "--compare deve existir");
+ assert.ok(optNames.includes("--save"), "--save deve existir");
+});
+
+test("test-provider — compare requer pelo menos dois modelos sem server retorna 0 ou 1", async () => {
+ const { runTestProviderCommand } = await import("../../bin/cli/commands/test-provider.mjs");
+ let code = 0;
+ try {
+ code = await runTestProviderCommand("anthropic", undefined, {
+ compare: "gpt-4o,claude-3-5-sonnet",
+ });
+ } catch {
+ code = 1;
+ }
+ assert.ok(code === 0 || code === 1);
+});