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

fix(antigravity): per-request Pro-family upstream-id fallback chain (#3786) (#3818)

Diego Rodrigues de Sa e Souza5b71b05a5e4b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0df8e616bb..7f578ec289 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@
### 🐛 Fixed
- **fix(intelligence): run pricing + models.dev sync from the live startup path** — like the Arena ELO sync (v3.8.24), the external **pricing sync** (`PRICING_SYNC_ENABLED`) and the **models.dev capability sync** (Settings → AI toggle) were only initialized from `server-init.ts`, which the Next standalone runtime never executes — and models.dev had no caller at all. Their toggles were inert in production. Both are now initialized from `instrumentation-node.ts` (self-gated, opt-in preserved, non-blocking, never fatal). (thanks @diegosouzapw)
+- **fix(antigravity): per-request Pro-family upstream-id fallback chain (`gemini-3.1-pro-high` 400)** — Antigravity silently renamed the Gemini 3.1 Pro-high upstream id, so `gemini-3.1-pro-high` started returning HTTP 400 (while `-low` still worked) and the live id can't be determined statically (competitor proxies disagree). The executor now retries alternative ids on a 400 (`gemini-3.1-pro-high` → `gemini-pro-agent` → `gemini-3-pro-high`, analogous for pro-low), bounded and only on a 400, with zero extra cost on the happy path; the 1:1 tier-passthrough invariant is preserved (the chain is request-time, not a static alias remap). ([#3786](https://github.com/diegosouzapw/OmniRoute/issues/3786) — thanks @aliaksandrsen)
- **fix(sse): retry once on an early stream close (`STREAM_EARLY_EOF`) for single-model requests** — flaky OpenAI-compatible upstreams (e.g. NVIDIA NIM with minimax-m3 / qwen3.5 / glm-5.1) intermittently send HTTP 200 then close the SSE with zero useful frames, surfacing as a 502 "Stream ended before producing useful content". Only Antigravity got an early-close retry; every other provider returned the 502 immediately on the non-combo single-model path. A bounded one-retry (early-close only — not readiness-timeout — and without marking the account unavailable) now generalizes it. (The separate qwen-web validation SSRF part of the same report was already fixed in v3.8.24, [#3767](https://github.com/diegosouzapw/OmniRoute/pull/3767).) ([#3758](https://github.com/diegosouzapw/OmniRoute/issues/3758) — thanks @Svatosalav)
- **fix(models): preserve eye-hidden models across auto-sync / import** — hiding models via the visibility (eye) toggle to keep only a combo's models was undone on every model import or auto-sync, which re-showed all of them. The sync re-import treated "hidden" identically to "deleted" and dropped both; a distinct `isDeleted` marker now separates the trash/delete path (still dropped on re-import, #3199) from the eye toggle (preserved as listed-but-hidden), and eye-hidden models are no longer re-aliased into the routable catalog on sync. ([#3782](https://github.com/diegosouzapw/OmniRoute/issues/3782) — thanks @xenstar)
- **fix(providers): correct the lmarena cookie hint (`session` → `arena-auth-prod-v1`)** — the lmarena credential hint asked for a cookie named `session`, but lmarena.ai's real auth cookie is `arena-auth-prod-v1`, so users who pasted only `session=…` hit validation failures. The credential name, placeholder and storage keys now use the correct name (the legacy `session` key is retained for back-compat with already-saved credentials). ([#3810](https://github.com/diegosouzapw/OmniRoute/issues/3810) — thanks @xspylol)
diff --git a/file-size-baseline.json b/file-size-baseline.json
index db150ae7e4..377e52fb41 100644
--- a/file-size-baseline.json
+++ b/file-size-baseline.json
@@ -3,7 +3,7 @@
"cap": 800,
"frozen": {
"open-sse/config/providerRegistry.ts": 4703,
- "open-sse/executors/antigravity.ts": 1572,
+ "open-sse/executors/antigravity.ts": 1649,
"open-sse/executors/base.ts": 1218,
"open-sse/executors/chatgpt-web.ts": 2870,
"open-sse/executors/claude-web.ts": 1057,
@@ -113,5 +113,6 @@
"_rebaseline_2026_06_12_v3823_new_features": "Re-baseline v3.8.23 pós-merge de #3742 (cost drilldown: ApiManagerPageClient.tsx +21, CostOverviewTab.tsx +14, providerLimits.ts +2, usage.ts +53) + #3743 (provider display modes: ProviderDetailPageClient.tsx +2, providerPageHelpers.ts +42, providers.ts +2) + #3740 (semantic cache key isolation: chat.ts +3). Crescimento justificado por features novas mergeadas no ciclo.",
"_rebaseline_2026_06_13_combo_quota_audit": "Re-baseline consciente do audit combo+quota (PR #3779): combo.ts 5054→5131 (+77). Crescimento = 5 fixes TDD + estratégia complexity-aware 2026 (W1 clampComboDepth + threading de maxDepth em 6 assinaturas/dispatch/DAG; W2 extração shouldSkipForPredictedTtft; W4 scoreAutoTargets exportado + param manifestHint). A parte limpa-extraível do W4 (construção do hint inline, ~30 linhas) FOI extraída para autoCombo/complexityRouter.ts (buildComplexityRoutingHint) — este +76 é o resíduo irredutível (edição de assinaturas/threading, não bloco movível). Shrink estrutural de combo.ts segue com #3501.",
"_rebaseline_2026_06_13_v3824_3776": "Re-baseline v3.8.24 pós #3776 (strict-mode controls Claude Code default models: ApiManagerPageClient.tsx 2701→2909 = UI de famílias bloqueáveis cc/* + chips; apiKeys.ts 1490→1633 = blocked_models deny-list + candidatos de permissão claude-code; schemas.ts 2515→2519 = reformatação Prettier + reasoningTokenBufferEnabled restaurado) + carry-over base.ts 1205→1218 do #3780 (enforceThinkingTemperature no chokepoint, drift de baseline não bumpado no merge). Crescimento de feature; sem god-component novo.",
+ "_rebaseline_2026_06_13_3786_agy_fallback": "Re-baseline #3786 (agy Pro-family upstream-id fallback chain): antigravity.ts 1572→1649 (+77). Crescimento = split de execute() em driver + executeOnce(modelIdOverride) para retentar ids alternativos no 400 (gemini-3.1-pro-high→gemini-pro-agent→gemini-3-pro-high), threading do override em transformRequest/cleanModelName. Lógica coesa de retry no executor — não é bloco movível (chama this.executeOnce). A parte pura (ANTIGRAVITY_PRO_FALLBACK_CHAINS + getAntigravityModelFallbacks) ficou em antigravityModelAliases.ts. Os 3 drifts release-wide (ProxyRegistryManager/sidebarVisibility/schemas) são do #3809 do owner, não deste PR.",
"_rebaseline_2026_06_13_3782_hide_persist": "Re-baseline #3782 (preservar modelos eye-hidden no auto-sync): models.ts 1132→1180 (+48). Crescimento = flag distinto isDeleted em ModelCompatOverride/ModelCompatPatch + handling em mergeModelCompatOverride + helper getModelIsDeleted, para separar 'deletado' (trash, dropado no re-sync #3199) de 'oculto' (eye toggle, preservado). Lógica coesa de visibilidade no módulo db; não-extraível. Os 3 drifts release-wide (ProxyRegistryManager/sidebarVisibility/schemas) são do #3809 do owner, não deste PR."
}
diff --git a/open-sse/config/antigravityModelAliases.ts b/open-sse/config/antigravityModelAliases.ts
index 0878f5ab7a..69f8e289cc 100644
--- a/open-sse/config/antigravityModelAliases.ts
+++ b/open-sse/config/antigravityModelAliases.ts
@@ -177,6 +177,47 @@ export const ANTIGRAVITY_MODEL_ALIASES = Object.freeze({
type AntigravityModelAliasMap = Record<string, string>;
+/**
+ * #3786 — Per-request upstream-id FALLBACK CHAINS for the Gemini 3.1 Pro family.
+ *
+ * On recent Antigravity versions `gemini-3.1-pro-high` started returning HTTP 400
+ * ("Antigravity upstream error (400)") while `gemini-3.1-pro-low` still works. The upstream
+ * changed the accepted id format for the Pro-high tier and the live id cannot be determined
+ * from static analysis — the two actively-maintained competitor proxies DISAGREE:
+ * - AntigravityManager → `gemini-3.1-pro-high`
+ * - CLIProxyAPI → `gemini-pro-agent` (display: "Gemini 3.1 Pro (High)")
+ * - older form → `gemini-3-pro-high`
+ *
+ * Mirroring AntigravityManager's robust approach, the executor retries the next candidate id
+ * on a 400 until one succeeds (2xx) or the chain is exhausted. This is a REQUEST-TIME retry,
+ * NOT a change to the static `resolveAntigravityModelId` map — the #3696 pass-through
+ * invariant (suffixed ids reach the upstream verbatim on the FIRST attempt) is preserved.
+ *
+ * Each chain starts with its own key so the happy path (first id 200) incurs zero extra
+ * calls, and every candidate is listed at most once so the retry loop is bounded.
+ */
+export const ANTIGRAVITY_PRO_FALLBACK_CHAINS: Readonly<Record<string, readonly string[]>> =
+ Object.freeze({
+ "gemini-3.1-pro-high": Object.freeze([
+ "gemini-3.1-pro-high",
+ "gemini-pro-agent",
+ "gemini-3-pro-high",
+ ]),
+ // pro-low currently works but is given a trivially-symmetric chain for resilience if the
+ // upstream renames it the same way it renamed pro-high.
+ "gemini-3.1-pro-low": Object.freeze(["gemini-3.1-pro-low", "gemini-3-pro-low"]),
+ });
+
+/**
+ * Return the ordered upstream-id fallback chain for `modelId` (the requested id first), or
+ * `[]` when the model has no chain (flash, claude, plain pro, etc.). Pure — safe to unit test
+ * and to call on every request (returns `[]` cheaply off the happy path's hot models).
+ */
+export function getAntigravityModelFallbacks(modelId: string): readonly string[] {
+ if (!modelId) return [];
+ return ANTIGRAVITY_PRO_FALLBACK_CHAINS[modelId] ?? [];
+}
+
export const ANTIGRAVITY_REVERSE_MODEL_ALIASES: AntigravityModelAliasMap = Object.freeze({
"gemini-3.5-flash-extra-low": "gemini-3.5-flash-low",
"gemini-3-flash-agent": "gemini-3.5-flash-high",
diff --git a/open-sse/executors/antigravity.ts b/open-sse/executors/antigravity.ts
index d55a9162b9..eb2cdc4db5 100644
--- a/open-sse/executors/antigravity.ts
+++ b/open-sse/executors/antigravity.ts
@@ -35,7 +35,10 @@ import { getMitmAlias } from "@/lib/db/models";
import { obfuscateSensitiveWords } from "../services/antigravityObfuscation.ts";
import { resolveAntigravityVersion } from "../services/antigravityVersion.ts";
import { ensureAntigravityProjectAssigned } from "../services/antigravityProjectBootstrap.ts";
-import { resolveAntigravityModelId } from "../config/antigravityModelAliases.ts";
+import {
+ resolveAntigravityModelId,
+ getAntigravityModelFallbacks,
+} from "../config/antigravityModelAliases.ts";
import { cloakAntigravityToolPayload } from "../config/toolCloaking.ts";
import {
shouldStripCloudCodeThinking,
@@ -429,8 +432,15 @@ function flushAntigravitySSEText(
/**
* Strip provider prefixes (e.g. "antigravity/model" → "model").
* Ensures the model name sent to the upstream API never contains a routing prefix.
+ *
+ * `modelIdOverride` (#3786): when the per-request Pro-family fallback chain forces a
+ * specific upstream id, pass it here. It is an ALREADY-RESOLVED upstream id, so it bypasses
+ * the MITM/static alias resolution and is used verbatim (after prefix stripping).
*/
-async function cleanModelName(model: string): Promise<string> {
+async function cleanModelName(model: string, modelIdOverride?: string): Promise<string> {
+ if (modelIdOverride) {
+ return modelIdOverride.includes("/") ? modelIdOverride.split("/").pop()! : modelIdOverride;
+ }
if (!model) return model;
const stripped = model.includes("/") ? model.split("/").pop()! : model;
let clean = stripped;
@@ -584,7 +594,8 @@ export class AntigravityExecutor extends BaseExecutor {
model: string,
body: unknown,
_stream: boolean,
- credentials: AntigravityCredentials
+ credentials: AntigravityCredentials,
+ modelIdOverride?: string
): Promise<AntigravityRequestEnvelope | Response> {
// Project ID resolution: prefer OAuth-stored projectId over incoming body.project
// to avoid stale/wrong client-side values causing 404/403 from Cloud Code endpoints.
@@ -660,7 +671,7 @@ export class AntigravityExecutor extends BaseExecutor {
return resp as unknown as never;
}
- const upstreamModel = await cleanModelName(model);
+ const upstreamModel = await cleanModelName(model, modelIdOverride);
const isClaude = upstreamModel.toLowerCase().includes("claude");
const baseBody = bodyRecord;
const normalizedBody = shouldStripCloudCodeThinking(this.provider, upstreamModel)
@@ -996,15 +1007,76 @@ export class AntigravityExecutor extends BaseExecutor {
return collect();
}
- async execute({
- model,
- body,
- stream,
- credentials,
- signal,
- log,
- upstreamExtraHeaders,
- }: ExecuteInput) {
+ /**
+ * #3786 — Drive the per-request Pro-family upstream-id FALLBACK CHAIN.
+ *
+ * The upstream silently renamed the Gemini 3.1 Pro-high id (HTTP 400 on the old id) and the
+ * live id cannot be known from static analysis (competitor proxies disagree). When the
+ * resolved upstream id has a fallback chain (see ANTIGRAVITY_PRO_FALLBACK_CHAINS) we try the
+ * requested id first and, ONLY on a 400, retry the next candidate until one succeeds (2xx)
+ * or the chain is exhausted — then the original 400 surfaces (sanitized, hard rule #12).
+ *
+ * Off the happy path entirely: a model with no chain, or whose first id is not a 400, makes
+ * exactly the same single call as before (zero extra upstream requests).
+ */
+ async execute(input: ExecuteInput) {
+ await resolveAntigravityVersion();
+
+ // Look up the chain by the NORMALLY-resolved upstream id (honours MITM/static aliases).
+ // If a MITM alias remapped the id away from a known Pro tier, no chain applies → fast path.
+ const resolvedUpstreamId = await cleanModelName(input.model);
+ const chain = getAntigravityModelFallbacks(resolvedUpstreamId);
+
+ if (chain.length <= 1) {
+ // No fallback chain (flash, claude, plain pro, unknown) → single attempt, unchanged.
+ return this.executeOnce(input);
+ }
+
+ let firstResult: Awaited<ReturnType<AntigravityExecutor["executeOnce"]>> | null = null;
+ for (let i = 0; i < chain.length; i++) {
+ const candidate = chain[i];
+ const result = await this.executeOnce(input, candidate);
+
+ // Success (or any non-400) on a candidate → return immediately.
+ if (result.response.status !== HTTP_STATUS.BAD_REQUEST) {
+ return result;
+ }
+
+ // Remember the FIRST 400 so the exhausted-chain case surfaces the original error.
+ if (i === 0) firstResult = result;
+
+ const isLast = i === chain.length - 1;
+ if (!isLast) {
+ input.log?.debug?.(
+ "AG_PRO_FALLBACK",
+ `400 on "${candidate}" — retrying with next Pro candidate "${chain[i + 1]}"`
+ );
+ continue;
+ }
+
+ // Chain exhausted: surface the FIRST candidate's sanitized 400.
+ input.log?.warn?.(
+ "AG_PRO_FALLBACK",
+ `Pro fallback chain exhausted (all ${chain.length} candidates 400'd) for "${resolvedUpstreamId}"`
+ );
+ return firstResult ?? result;
+ }
+
+ // Unreachable (loop always returns), but keeps the type checker happy.
+ return firstResult ?? this.executeOnce(input);
+ }
+
+ /**
+ * #3786 — Run the request once for a SINGLE resolved upstream model id. The Pro-family
+ * fallback chain in `execute()` calls this per candidate (`modelIdOverride`), retrying the
+ * next id on a 400. `modelIdOverride === undefined` is the normal (non-chain) path and
+ * preserves the prior behavior exactly. Returns the executor result plus the upstream
+ * status of the first response so `execute()` can decide whether to fall through. @internal
+ */
+ private async executeOnce(
+ { model, body, stream, credentials, signal, log, upstreamExtraHeaders }: ExecuteInput,
+ modelIdOverride?: string
+ ) {
await resolveAntigravityVersion();
const fallbackCount = this.getFallbackCount();
let lastError = null;
@@ -1071,7 +1143,13 @@ export class AntigravityExecutor extends BaseExecutor {
const url = this.buildUrl(model, upstreamStream, urlIndex);
const headers = this.buildHeaders(credentials, upstreamStream);
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
- const transformed = await this.transformRequest(model, body, upstreamStream, credentials);
+ const transformed = await this.transformRequest(
+ model,
+ body,
+ upstreamStream,
+ credentials,
+ modelIdOverride
+ );
let requestToolNameMap: Map<string, string> | null = null;
if (transformed instanceof Response) {
@@ -1294,7 +1372,6 @@ export class AntigravityExecutor extends BaseExecutor {
log?.warn?.("AG_CREDITS", `Credits retry failed: ${creditsErr}`);
}
}
-
} catch (e) {
// Ignore parse errors, will fall back to exponential backoff
}
diff --git a/tests/unit/agy-pro-fallback-chain-3786.test.ts b/tests/unit/agy-pro-fallback-chain-3786.test.ts
new file mode 100644
index 0000000000..1f76ddc4d1
--- /dev/null
+++ b/tests/unit/agy-pro-fallback-chain-3786.test.ts
@@ -0,0 +1,219 @@
+/**
+ * #3786 — Antigravity (`agy` / `antigravity`) `gemini-3.1-pro-high` returns HTTP 400
+ * ("Antigravity upstream error (400)") on recent upstream versions; `gemini-3.1-pro-low`
+ * still works. OmniRoute sends the requested id VERBATIM (per #3696 wire capture). The
+ * upstream changed the accepted model-id format for the Pro-high tier and the two
+ * actively-maintained competitor proxies DISAGREE on the live id:
+ * - AntigravityManager → `gemini-3.1-pro-high`
+ * - CLIProxyAPI → `gemini-pro-agent` (display: "Gemini 3.1 Pro (High)")
+ * - older form → `gemini-3-pro-high`
+ *
+ * Because the live id cannot be known from static analysis, we mirror AntigravityManager's
+ * ROBUST approach: a per-request FALLBACK CHAIN that retries alternative upstream ids on a
+ * 400, until one succeeds (2xx) or the chain is exhausted (then the original 400 surfaces,
+ * sanitized — hard rule #12).
+ *
+ * The fallback chain lives at EXECUTOR REQUEST-TIME (retry on 400). It is NOT a change to
+ * the static `resolveAntigravityModelId` map, so the #3696 invariant test stays green.
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ ANTIGRAVITY_PRO_FALLBACK_CHAINS,
+ getAntigravityModelFallbacks,
+} from "../../open-sse/config/antigravityModelAliases.ts";
+import { AntigravityExecutor } from "../../open-sse/executors/antigravity.ts";
+import { seedAntigravityVersionCache } from "../../open-sse/services/antigravityVersion.ts";
+
+type ChatCompletionPayload = {
+ object?: string;
+ choices: Array<{ message: { content: string }; finish_reason: string }>;
+};
+
+type ErrorPayload = {
+ error: { code?: string; message: string };
+};
+
+// ---------------------------------------------------------------------------
+// Pure helper: getAntigravityModelFallbacks
+// ---------------------------------------------------------------------------
+
+test("(#3786) getAntigravityModelFallbacks returns the ordered pro-high chain", () => {
+ assert.deepEqual(getAntigravityModelFallbacks("gemini-3.1-pro-high"), [
+ "gemini-3.1-pro-high",
+ "gemini-pro-agent",
+ "gemini-3-pro-high",
+ ]);
+});
+
+test("(#3786) getAntigravityModelFallbacks returns the ordered pro-low chain", () => {
+ assert.deepEqual(getAntigravityModelFallbacks("gemini-3.1-pro-low"), [
+ "gemini-3.1-pro-low",
+ "gemini-3-pro-low",
+ ]);
+});
+
+test("(#3786) getAntigravityModelFallbacks returns [] for unrelated models", () => {
+ assert.deepEqual(getAntigravityModelFallbacks("gemini-2.5-flash"), []);
+ assert.deepEqual(getAntigravityModelFallbacks("claude-sonnet-4-6"), []);
+ assert.deepEqual(getAntigravityModelFallbacks("gemini-3-pro-preview"), []);
+ assert.deepEqual(getAntigravityModelFallbacks(""), []);
+});
+
+test("(#3786) every chain starts with its own key (each candidate listed once)", () => {
+ for (const [key, chain] of Object.entries(ANTIGRAVITY_PRO_FALLBACK_CHAINS)) {
+ assert.equal(chain[0], key, `chain for ${key} must start with itself`);
+ assert.equal(new Set(chain).size, chain.length, `chain for ${key} must have no duplicates`);
+ }
+});
+
+// ---------------------------------------------------------------------------
+// Behavioral: executor retries the next candidate on a 400
+// ---------------------------------------------------------------------------
+
+function makeSuccessSSE(): Response {
+ return new Response(
+ 'data: {"response":{"candidates":[{"content":{"parts":[{"text":"OK"}]},"finishReason":"STOP"}]}}\n\n',
+ { status: 200, headers: { "Content-Type": "text/event-stream" } }
+ );
+}
+
+function make400(modelId: string): Response {
+ return new Response(
+ JSON.stringify({ error: { code: 400, message: `Model not found: ${modelId}` } }),
+ { status: 400, headers: { "Content-Type": "application/json" } }
+ );
+}
+
+/** Extract the upstream model id from the serialized request envelope. */
+function envelopeModel(init: RequestInit | undefined): string {
+ try {
+ return JSON.parse(String(init?.body)).model as string;
+ } catch {
+ return "";
+ }
+}
+
+test("(#3786) execute retries pro-high with the next candidate when the first id 400s", async () => {
+ const executor = new AntigravityExecutor();
+ const originalFetch = globalThis.fetch;
+ seedAntigravityVersionCache("2026.04.17-test");
+ const modelsTried: string[] = [];
+
+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {
+ const m = envelopeModel(init);
+ modelsTried.push(m);
+ // First candidate (gemini-3.1-pro-high) → 400, second (gemini-pro-agent) → 200
+ if (m === "gemini-3.1-pro-high") return make400(m);
+ return makeSuccessSSE();
+ }) as typeof fetch;
+
+ try {
+ const result = await executor.execute({
+ model: "antigravity/gemini-3.1-pro-high",
+ body: { request: { contents: [] } },
+ stream: false,
+ credentials: { accessToken: "token", projectId: "project-1" },
+ log: { debug() {}, warn() {}, info() {} },
+ });
+ const payload = (await result.response.json()) as ChatCompletionPayload;
+
+ assert.equal(result.response.status, 200, "second candidate should succeed");
+ assert.equal(payload.choices[0].message.content, "OK");
+ // Exactly two upstream calls: the 400 then the 200 on the next id.
+ assert.deepEqual(modelsTried, ["gemini-3.1-pro-high", "gemini-pro-agent"]);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("(#3786) execute exhausts the chain on all-400 and surfaces a sanitized 400 (each candidate tried once)", async () => {
+ const executor = new AntigravityExecutor();
+ const originalFetch = globalThis.fetch;
+ seedAntigravityVersionCache("2026.04.17-test");
+ const modelsTried: string[] = [];
+
+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {
+ const m = envelopeModel(init);
+ modelsTried.push(m);
+ return make400(m); // every candidate fails with 400
+ }) as typeof fetch;
+
+ try {
+ const result = await executor.execute({
+ model: "antigravity/gemini-3.1-pro-high",
+ body: { request: { contents: [] } },
+ stream: false,
+ credentials: { accessToken: "token", projectId: "project-1" },
+ log: { debug() {}, warn() {}, info() {} },
+ });
+ const payload = (await result.response.json()) as ErrorPayload;
+
+ // Surfaces a real, sanitized 400 — not a masked empty chat.completion.
+ assert.equal(result.response.status, 400);
+ assert.ok(payload.error, "must carry an error object");
+ assert.equal(typeof payload.error.message, "string");
+ assert.ok(!payload.error.message.includes("at /"), "no raw stack trace (hard rule #12)");
+
+ // Each candidate tried EXACTLY once (bounded — no infinite loop).
+ assert.deepEqual(modelsTried, ["gemini-3.1-pro-high", "gemini-pro-agent", "gemini-3-pro-high"]);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("(#3786) happy path: first id 200 makes exactly ONE upstream call (zero extra)", async () => {
+ const executor = new AntigravityExecutor();
+ const originalFetch = globalThis.fetch;
+ seedAntigravityVersionCache("2026.04.17-test");
+ const modelsTried: string[] = [];
+
+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {
+ modelsTried.push(envelopeModel(init));
+ return makeSuccessSSE();
+ }) as typeof fetch;
+
+ try {
+ const result = await executor.execute({
+ model: "antigravity/gemini-3.1-pro-high",
+ body: { request: { contents: [] } },
+ stream: false,
+ credentials: { accessToken: "token", projectId: "project-1" },
+ log: { debug() {}, warn() {}, info() {} },
+ });
+
+ assert.equal(result.response.status, 200);
+ assert.deepEqual(modelsTried, ["gemini-3.1-pro-high"], "exactly one call on the happy path");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("(#3786) a non-pro model that 400s does NOT trigger the fallback chain", async () => {
+ const executor = new AntigravityExecutor();
+ const originalFetch = globalThis.fetch;
+ seedAntigravityVersionCache("2026.04.17-test");
+ const modelsTried: string[] = [];
+
+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {
+ modelsTried.push(envelopeModel(init));
+ return make400(envelopeModel(init));
+ }) as typeof fetch;
+
+ try {
+ const result = await executor.execute({
+ model: "antigravity/gemini-2.5-flash",
+ body: { request: { contents: [] } },
+ stream: false,
+ credentials: { accessToken: "token", projectId: "project-1" },
+ log: { debug() {}, warn() {}, info() {} },
+ });
+
+ // flash 400 surfaces directly — only the requested id is tried, no chain.
+ assert.equal(result.response.status, 400);
+ assert.deepEqual(modelsTried, ["gemini-2.5-flash"]);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});