fix(antigravity): honor fresh account catalog wire IDs (#16254)

A fresh Antigravity account catalog wire ID is kept for that connection. Tiered-only accounts still use tiered routing, and explicit overrides stay first.

Boarded on release/v3.8.52 at e01340c854. Focused tests: 317 passed. File-size kept only the inherited executeTargetAttempt.ts overage (1288 > 1284). This pull request does not touch that file.

⚠️ base-red inherited: #15306
Fixes #16237
This commit is contained in:
Diego Rodrigues de Sa e Souza
2026-10-13 14:45:07 -03:00
committed by GitHub
parent 14d458dc90
commit 44292502bf
9 changed files with 554 additions and 77 deletions

View File

@@ -0,0 +1 @@
- Resolve Antigravity Gemini 3.7 Flash high/medium/low requests against the fresh catalog of the selected connection before global aliases, preserving tiered-only accounts and rechecking the same connection after a 404 discovery sync. Explicit overrides, other model families, stale-catalog fallback and conservative concurrency leases retain their existing behavior. Fixes #16237.

View File

@@ -24,7 +24,8 @@ import {
import { persistCreditBalance, getAllPersistedCreditBalances } from "@/lib/db/creditBalance";
import { setConnectionRateLimitUntil } from "@/lib/db/providers";
import { markAntigravityModelQuotaExhausted } from "../services/antigravityFamilyCooldown.ts";
import { getMitmAlias } from "@/lib/db/models";
import { cleanModelName } from "./antigravity/modelResolution.ts";
export { cleanModelName } from "./antigravity/modelResolution.ts";
import { resolveAntigravityOutputCap } from "./antigravityOutputCap.ts";
export { MAX_ANTIGRAVITY_OUTPUT_TOKENS } from "./antigravityOutputCap.ts";
import {
@@ -33,10 +34,7 @@ import {
} from "../services/antigravityProjectBootstrap.ts";
import { persistDiscoveredAntigravityProjectId } from "../services/antigravityProjectPersist.ts";
import { markAntigravityMissingCloudCodeProject } from "../services/antigravityProjectPersistence.ts";
import {
resolveAntigravityModelId,
getAntigravityModelFallbacks,
} from "../config/antigravityModelAliases.ts";
import { getAntigravityModelFallbacks } from "../config/antigravityModelAliases.ts";
import {
shouldStripCloudCodeThinking,
stripCloudCodeThinkingConfig,
@@ -260,54 +258,6 @@ export function markConnectionQuotaExhausted(
* tests (the markdown / candidate-parts extraction branches). @internal
*/
/**
* 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).
*/
export async function cleanModelName(
model: string,
modelIdOverride?: string,
provider = "antigravity"
): 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;
// 1. Check dynamic MITM aliases first (authoritative after first sync).
// Built during model sync — contains ONLY currently-available models.
// Obsolete/removed models are automatically excluded.
try {
const mitmAliases = await getMitmAlias(provider);
if (mitmAliases && typeof mitmAliases === "object") {
const aliases = mitmAliases as Record<string, unknown>;
const raw = aliases[stripped];
// Only honor string aliases; corrupted/non-string DB values fall through
// to the static alias resolution below (never return undefined here).
if (typeof raw === "string" && raw) {
// Strip the provider prefix if present; use the raw model ID otherwise.
const prefix = `${provider}/`;
clean = raw.startsWith(prefix) ? raw.slice(prefix.length) : raw;
}
}
} catch {
// DB not available (build phase, transient error) — fall through to static aliases
}
// 2. Fall back to static aliases if MITM didn't resolve
if (clean === stripped) {
clean = resolveAntigravityModelId(clean);
}
return clean;
}
function applyAntigravityGenerationDefaults(
request: Record<string, unknown>,
modelId?: string | null
@@ -721,7 +671,12 @@ export class AntigravityExecutor extends BaseExecutor {
return resp as unknown as never;
}
const upstreamModel = await cleanModelName(model, modelIdOverride);
const upstreamModel = await cleanModelName(
model,
modelIdOverride,
this.provider,
credentials?.connectionId
);
const isClaude = upstreamModel.toLowerCase().includes("claude");
// #10104: newer Gemini endpoints reject a request ending on a `model` turn with
// HTTP 400 "Requests ending with a model turn are not supported" — the same
@@ -1179,7 +1134,12 @@ export class AntigravityExecutor extends BaseExecutor {
// 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 resolvedUpstreamId = await cleanModelName(
input.model,
undefined,
this.provider,
input.credentials.connectionId
);
const chain = getAntigravityModelFallbacks(resolvedUpstreamId);
if (chain.length <= 1) {

View File

@@ -401,7 +401,12 @@ export async function sendAntigravityRequest(
// module) forms an async ESM init cycle that deadlocks the bundled MCP server
// on startup (tests/unit/build/mcp-bundle-startup.test.ts).
const { cleanModelName } = await import("../antigravity.ts");
const reResolvedModel = await cleanModelName(model, undefined, provider);
const reResolvedModel = await cleanModelName(
model,
undefined,
provider,
credentials.connectionId
);
const retryBody: Record<string, unknown> = {
...transformedBody,
model: reResolvedModel,

View File

@@ -0,0 +1,64 @@
import {
getMitmAlias,
getFreshAntigravityModelsForConnection,
} from "../../../src/lib/db/models.ts";
import { resolveAntigravityModelId } from "../../config/antigravityModelAliases.ts";
const ACCOUNT_FLASH_TIERS = new Set([
"gemini-3.7-flash-high",
"gemini-3.7-flash-medium",
"gemini-3.7-flash-low",
]);
async function resolveAccountModel(model: string, connectionId?: string): Promise<string | null> {
if (!connectionId || !ACCOUNT_FLASH_TIERS.has(model)) return null;
try {
const models = await getFreshAntigravityModelsForConnection(connectionId);
if (models.some((entry) => entry.id === model)) return model;
if (models.some((entry) => entry.id === "gemini-3.7-flash-tiered")) {
return "gemini-3.7-flash-tiered";
}
} catch {
// An unavailable DB must retain the existing MITM/static fallback.
}
return null;
}
/**
* 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).
*/
export async function cleanModelName(
model: string,
modelIdOverride?: string,
provider = "antigravity",
connectionId?: string
): Promise<string> {
if (modelIdOverride) {
return modelIdOverride.includes("/") ? modelIdOverride.split("/").pop()! : modelIdOverride;
}
if (!model) return model;
const stripped = model.includes("/") ? model.split("/").pop()! : model;
const accountModel = await resolveAccountModel(stripped, connectionId);
if (accountModel) return accountModel;
const legacy = await resolveLegacyAlias(stripped, provider);
return legacy === stripped ? resolveAntigravityModelId(stripped) : legacy;
}
async function resolveLegacyAlias(model: string, provider: string): Promise<string> {
try {
const mappings = await getMitmAlias(provider);
if (!mappings || typeof mappings !== "object") return model;
const alias = (mappings as Record<string, unknown>)[model];
if (typeof alias !== "string" || !alias) return model;
const prefix = `${provider}/`;
return alias.startsWith(prefix) ? alias.slice(prefix.length) : alias;
} catch {
// Preserve the static fallback when the DB or stored MITM JSON is unavailable.
return model;
}
}

View File

@@ -7,6 +7,7 @@
import { isRetiredGitHubCopilotModelId } from "@omniroute/open-sse/config/providers/registry/github/retiredModels.ts";
import { getDbInstance } from "./core";
import { isSyncedAtFresh } from "./models/syncedCatalogFreshness";
import { getProviderConnectionsCount, touchConnectionSyncedModelsAt } from "./providers";
import { type JsonRecord, getKeyValue } from "./models/shared";
import {
@@ -424,6 +425,20 @@ export async function getSyncedAvailableModelsForConnection(
}
}
/** Read only the active selected Antigravity account's fresh catalog, never its siblings. */
export async function getFreshAntigravityModelsForConnection(
connectionId: string
): Promise<SyncedAvailableModel[]> {
const row = getDbInstance()
.prepare(
`SELECT provider, synced_models_at AS syncedModelsAt FROM provider_connections
WHERE id = ? AND is_active = 1 AND provider IN ('antigravity', 'agy')`
)
.get(connectionId) as { provider: string; syncedModelsAt: string | null } | undefined;
if (!row || !isSyncedAtFresh(row.syncedModelsAt)) return [];
return getSyncedAvailableModelsForConnection(row.provider, connectionId);
}
/**
* Get all synced available models for a provider, unioned across all connections.
*/

View File

@@ -16,6 +16,7 @@ import {
} from "../models";
import { normalizeSyncedAvailableModels } from "./synced";
import { getRawProviderConnections } from "../providers";
import { isSyncedAtFresh } from "./syncedCatalogFreshness";
export type ActiveSyncedCatalog = {
authoritative: boolean;
@@ -51,27 +52,6 @@ type ProviderConnectionRef = {
syncedModelsAt: string | null;
};
// #12849: a connection synced once and never refreshed must not pin routing to
// that point-in-time snapshot forever — a live model the provider has since
// added would be rejected as "unavailable" indefinitely. Once the synced
// catalog exceeds this age (or was never timestamped — pre-migration rows),
// getActiveSyncedCatalog stops treating it as authoritative and fails open,
// matching the existing no-sync-yet behavior. Overridable for ops/testing.
const DEFAULT_SYNCED_CATALOG_STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
function getSyncedCatalogStaleAfterMs(): number {
const raw = process.env.OMNIROUTE_SYNCED_CATALOG_STALE_AFTER_MS;
const parsed = raw !== undefined ? Number(raw) : NaN;
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SYNCED_CATALOG_STALE_AFTER_MS;
}
function isSyncedAtFresh(syncedModelsAt: string | null): boolean {
if (!syncedModelsAt) return false;
const syncedAtMs = Date.parse(syncedModelsAt);
if (Number.isNaN(syncedAtMs)) return false;
return Date.now() - syncedAtMs <= getSyncedCatalogStaleAfterMs();
}
function resolveStoredProviderId(aliasOrId: string): string {
const normalized = aliasOrId.trim();
if (!normalized) return "";

View File

@@ -0,0 +1,20 @@
// #12849: a connection synced once and never refreshed must not pin routing to
// that point-in-time snapshot forever — a live model the provider has since
// added would be rejected as "unavailable" indefinitely. Once the synced
// catalog exceeds this age (or was never timestamped — pre-migration rows),
// getActiveSyncedCatalog stops treating it as authoritative and fails open,
// matching the existing no-sync-yet behavior. Overridable for ops/testing.
const DEFAULT_SYNCED_CATALOG_STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
function getSyncedCatalogStaleAfterMs(): number {
const raw = process.env.OMNIROUTE_SYNCED_CATALOG_STALE_AFTER_MS;
const parsed = raw !== undefined ? Number(raw) : NaN;
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SYNCED_CATALOG_STALE_AFTER_MS;
}
export function isSyncedAtFresh(syncedModelsAt: string | null): boolean {
if (!syncedModelsAt) return false;
const syncedAtMs = Date.parse(syncedModelsAt);
if (Number.isNaN(syncedAtMs)) return false;
return Date.now() - syncedAtMs <= getSyncedCatalogStaleAfterMs();
}

View File

@@ -0,0 +1,155 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dataDir = mkdtempSync(join(tmpdir(), "antigravity-resync-16237-"));
process.env.DATA_DIR = dataDir;
process.env.DISABLE_SQLITE_AUTO_BACKUP = "true";
const { getDbInstance, resetDbInstance } = await import("../../src/lib/db/core.ts");
const { replaceSyncedAvailableModelsForConnection, getSyncedAvailableModelsForConnection } =
await import("../../src/lib/db/models.ts");
const { AntigravityExecutor } = await import("../../open-sse/executors/antigravity.ts");
const { __resetReactiveModelSyncForTests } =
await import("../../src/lib/providerModels/reactiveModelSync.ts");
const { seedAntigravityIdeVersionCache } =
await import("../../open-sse/services/antigravityVersion.ts");
const literal = "gemini-3.7-flash-high";
const tiered = "gemini-3.7-flash-tiered";
const connectionId = "selected-resync-account";
const originalFetch = globalThis.fetch;
type Wire = { model: string; project: string; requestId: string; request: unknown };
function seed(provider: string) {
const db = getDbInstance();
const now = new Date().toISOString();
db.prepare(
`INSERT OR REPLACE INTO provider_connections
(id, provider, is_active, synced_models_at, created_at, updated_at)
VALUES (?, ?, 1, ?, ?, ?)`
).run(connectionId, provider, now, now, now);
db.prepare("INSERT OR REPLACE INTO key_value (namespace,key,value) VALUES (?, ?, ?)").run(
"syncedAvailableModels",
`${provider}:${connectionId}`,
JSON.stringify([{ id: tiered }])
);
}
async function executeResync(provider: string, abortAfterSync = false) {
seed(provider);
const wires: Wire[] = [];
const urls: string[] = [];
const signals: AbortSignal[] = [];
const telemetry: string[] = [];
let syncCount = 0;
const controller = new AbortController();
const reason = new DOMException("synthetic cancellation", "AbortError");
globalThis.fetch = async (input, init) => {
const url = new URL(String(input));
assert.equal(init?.method, "POST");
if (url.pathname === `/api/providers/${connectionId}/sync-models`) {
assert.equal(url.hostname, "127.0.0.1");
assert.equal(init.redirect, "error");
assert.ok(new Headers(init.headers).has("x-model-sync-internal-auth"));
syncCount++;
// Intercept only HTTP transport. The real reactive-sync/scheduler calls this
// boundary; the real DB writer persists the synthetic discovery result.
await replaceSyncedAvailableModelsForConnection(provider, connectionId, [{ id: literal }]);
if (abortAfterSync) controller.abort(reason);
return Response.json({ syncedModels: 1 });
}
assert.equal(url.pathname, "/v1internal:streamGenerateContent");
assert.equal(url.search, "?alt=sse");
assert.equal(typeof init.body, "string");
assert.ok(init.signal instanceof AbortSignal);
assert.equal(new Headers(init.headers).get("Authorization"), "Bearer synthetic-token");
urls.push(url.href);
signals.push(init.signal);
wires.push(JSON.parse(String(init.body)));
if (init.signal.aborted) throw init.signal.reason;
if (wires.length === 1)
return Response.json({ error: { message: "model not found" } }, { status: 404 });
return new Response(
'data: {"response":{"candidates":[{"content":{"parts":[{"text":"resynced"}]},"finishReason":"STOP"}]}}\n\n',
{
headers: { "Content-Type": "text/event-stream" },
}
);
};
const body = { request: { contents: [{ role: "user", parts: [{ text: "hello" }] }] } };
const before = structuredClone(body);
try {
const pending = new AntigravityExecutor().execute({
model: literal,
body,
stream: true,
signal: controller.signal,
credentials: { connectionId, accessToken: "synthetic-token", projectId: "synthetic-project" },
log: {
debug(_scope, message) {
telemetry.push(message);
},
warn() {},
info() {},
},
});
if (abortAfterSync) await assert.rejects(pending, (error) => error === reason);
else {
const result = await pending;
assert.equal(result.response.status, 200);
assert.match(await result.response.text(), /resynced/);
}
assert.deepEqual(body, before, "caller request remains unchanged");
assert.equal(syncCount, 1);
assert.equal(wires.length, 2);
assert.equal(wires[0].model, tiered);
assert.equal(wires[1].model, literal);
assert.equal(urls[0], urls[1]);
assert.notEqual(wires[0].requestId, wires[1].requestId);
assert.deepEqual(wires[0].request, wires[1].request);
assert.equal(wires[0].project, wires[1].project);
assert.equal(telemetry.filter((line) => line.includes("[Antigravity] PhysicalSend")).length, 2);
const stored = await getSyncedAvailableModelsForConnection(provider, connectionId);
assert.deepEqual(
stored.map((entry) => entry.id),
[literal]
);
if (abortAfterSync) assert.equal(signals[1].reason, reason);
} finally {
globalThis.fetch = originalFetch;
}
}
test.beforeEach(() => {
__resetReactiveModelSyncForTests();
seedAntigravityIdeVersionCache("2.1.1");
const db = getDbInstance();
db.prepare("DELETE FROM provider_connections").run();
db.prepare(
"DELETE FROM key_value WHERE namespace IN ('syncedAvailableModels', 'mitmAlias')"
).run();
db.prepare(
"INSERT INTO key_value (namespace,key,value) VALUES ('mitmAlias','antigravity',?)"
).run(JSON.stringify({ [literal]: `antigravity/${tiered}` }));
});
test.after(() => {
globalThis.fetch = originalFetch;
__resetReactiveModelSyncForTests();
// The real catalog writer schedules reconciliation asynchronously. Let the
// event loop drain naturally before closing/removing its database.
process.once("beforeExit", () => {
resetDbInstance();
rmSync(dataDir, { recursive: true, force: true });
});
});
for (const provider of ["antigravity", "agy"]) {
test(`404 resync re-reads the same ${provider} account before its bounded retry`, async () => {
await executeResync(provider);
});
}
test("cancellation after successful resync propagates to the rebuilt retry", async () => {
await executeResync("antigravity", true);
});

View File

@@ -0,0 +1,277 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dataDir = mkdtempSync(join(tmpdir(), "antigravity-wire-16237-"));
process.env.DATA_DIR = dataDir;
process.env.DISABLE_SQLITE_AUTO_BACKUP = "true";
const { getDbInstance, resetDbInstance } = await import("../../src/lib/db/core.ts");
const { AntigravityExecutor, cleanModelName } =
await import("../../open-sse/executors/antigravity.ts");
const { seedAntigravityIdeVersionCache, seedAntigravityCliVersionCache } =
await import("../../open-sse/services/antigravityVersion.ts");
const literal = "gemini-3.7-flash-high";
const tiered = "gemini-3.7-flash-tiered";
const originalFetch = globalThis.fetch;
function seed(connectionId: string, ids: string[], provider = "antigravity") {
const db = getDbInstance();
const now = new Date().toISOString();
db.prepare(
`INSERT OR REPLACE INTO provider_connections
(id, provider, is_active, synced_models_at, created_at, updated_at)
VALUES (?, ?, 1, ?, ?, ?)`
).run(connectionId, provider, now, now, now);
db.prepare("INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES (?, ?, ?)").run(
"syncedAvailableModels",
`${provider}:${connectionId}`,
JSON.stringify(ids.map((id) => ({ id })))
);
}
async function dispatch(connectionId: string | undefined, model = literal) {
const wires: Array<{ model: string; project: string; request: unknown }> = [];
globalThis.fetch = async (url, init) => {
assert.match(String(url), /\/v1internal:streamGenerateContent\?alt=sse$/);
assert.equal(init?.method, "POST");
assert.equal(typeof init.body, "string");
assert.ok(init.signal instanceof AbortSignal);
wires.push(JSON.parse(String(init.body)));
return new Response(
'data: {"response":{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}\n\n',
{
headers: { "Content-Type": "text/event-stream" },
}
);
};
try {
const result = await new AntigravityExecutor().execute({
model,
body: { request: { contents: [{ role: "user", parts: [{ text: "hello" }] }] } },
stream: true,
credentials: { connectionId, accessToken: "synthetic-token", projectId: "synthetic-project" },
log: { debug() {}, warn() {} },
});
assert.equal(result.response.status, 200);
assert.match(await result.response.text(), /ok/);
assert.equal(wires.length, 1);
assert.equal(wires[0].project, "synthetic-project");
return wires[0].model;
} finally {
globalThis.fetch = originalFetch;
}
}
test.beforeEach(() => {
const db = getDbInstance();
db.prepare("DELETE FROM provider_connections").run();
db.prepare(
"DELETE FROM key_value WHERE namespace IN ('syncedAvailableModels', 'mitmAlias')"
).run();
db.prepare(
"INSERT INTO key_value (namespace, key, value) VALUES ('mitmAlias', 'antigravity', ?)"
).run(JSON.stringify({ [literal]: `antigravity/${tiered}` }));
seedAntigravityIdeVersionCache("2.1.1");
seedAntigravityCliVersionCache("1.1.5");
});
test.after(() => {
globalThis.fetch = originalFetch;
resetDbInstance();
rmSync(dataDir, { recursive: true, force: true });
});
test("fresh selected account sends its literal 3.7 id before global MITM aliases", async () => {
seed("literal-account", [literal, tiered]);
seed("tiered-account", [tiered]);
assert.equal(await dispatch("literal-account"), literal);
});
test("tiered-only selected account retains tiered wire id despite another account's literal", async () => {
seed("literal-account", [literal]);
seed("tiered-account", [tiered]);
assert.equal(await dispatch("tiered-account"), tiered);
});
test("missing selected account retains the existing MITM/static fallback", async () => {
seed("other-account", [literal]);
assert.equal(await dispatch("missing-account"), tiered);
});
for (const tier of ["high", "medium", "low"]) {
for (const provider of ["antigravity", "agy"]) {
test(`${provider} ${tier} literal-only catalog wins without MITM`, async () => {
const id = `gemini-3.7-flash-${tier}`;
getDbInstance().prepare("DELETE FROM key_value WHERE namespace = 'mitmAlias'").run();
seed("selected", [id], provider);
assert.equal(await dispatch("selected", `${provider}/${id}`), id);
});
}
}
test("selected-account lookup prevents an unrelated global Pro fallback chain", async () => {
seed("selected", [literal]);
getDbInstance()
.prepare("UPDATE key_value SET value = ? WHERE namespace = 'mitmAlias'")
.run(JSON.stringify({ [literal]: "antigravity/gemini-3.1-pro-low" }));
assert.equal(await dispatch("selected"), literal);
});
test("fresh tiered-only evidence also precedes a different global MITM mapping", async () => {
seed("selected", [tiered]);
getDbInstance()
.prepare("UPDATE key_value SET value = ? WHERE namespace = 'mitmAlias'")
.run(JSON.stringify({ [literal]: "antigravity/old-target" }));
assert.equal(await dispatch("selected"), tiered);
});
test("successive account selections and catalog replacements never reuse a sibling snapshot", async () => {
seed("a", [literal]);
seed("b", [tiered]);
assert.equal(await dispatch("b"), tiered);
assert.equal(await dispatch("a"), literal);
seed("a", [tiered]);
seed("b", [literal]);
assert.equal(await dispatch("a"), tiered);
assert.equal(await dispatch("b"), literal);
});
for (const [label, timestamp] of [
["missing", null],
["invalid", "not-a-date"],
["expired", new Date(Date.now() - 31 * 86400000).toISOString()],
]) {
test(`${label} timestamp cannot borrow freshness from another account`, async () => {
seed("selected", [literal]);
seed("other", [literal]);
getDbInstance()
.prepare("UPDATE provider_connections SET synced_models_at = ? WHERE id = ?")
.run(timestamp, "selected");
assert.equal(await dispatch("selected"), tiered);
});
}
for (const [label, content] of [
["empty", "[]"],
["malformed JSON", "{"],
["wrong shape", "{}"],
["invalid entries", '[null,{"id":5}]'],
["unrelated models", '[{"id":"other"}]'],
]) {
test(`${label} catalog keeps existing fallback`, async () => {
seed("selected", [literal]);
getDbInstance()
.prepare("UPDATE key_value SET value = ? WHERE namespace = 'syncedAvailableModels'")
.run(content);
assert.equal(await dispatch("selected"), tiered);
});
}
test("inactive connection cannot authorize its literal", async () => {
seed("selected", [literal]);
getDbInstance()
.prepare("UPDATE provider_connections SET is_active = 0 WHERE id = ?")
.run("selected");
assert.equal(await dispatch("selected"), tiered);
});
test("another provider's connection cannot authorize an Antigravity literal", async () => {
seed("selected", [literal], "openai");
assert.equal(await dispatch("selected"), tiered);
});
test("catalog key must match the stored provider identity as well as connection id", async () => {
seed("selected", [literal], "agy");
getDbInstance()
.prepare("UPDATE key_value SET key = ? WHERE namespace = 'syncedAvailableModels'")
.run("antigravity:selected");
assert.equal(await dispatch("selected"), tiered);
});
test("provider-wide custom models are not account evidence", async () => {
seed("selected", []);
getDbInstance()
.prepare(
"INSERT OR REPLACE INTO key_value (namespace,key,value) VALUES ('customModels','antigravity',?)"
)
.run(JSON.stringify([{ id: literal }]));
assert.equal(await dispatch("selected"), tiered);
});
test("omitted connection preserves the public legacy helper and executor contract", async () => {
seed("selected", [literal]);
assert.equal(await cleanModelName(`antigravity/${literal}`), tiered);
assert.equal(await dispatch(undefined), tiered);
});
test("explicit override still wins over fresh account and MITM", async () => {
seed("selected", [literal]);
const result = await new AntigravityExecutor().transformRequest(
literal,
{ request: { contents: [] } },
true,
{ connectionId: "selected", projectId: "synthetic-project" },
"antigravity/forced-wire-id"
);
assert.ok(!(result instanceof Response));
assert.equal(result.model, "forced-wire-id");
});
for (const [requested, expected] of [
["gemini-3.7-flash", tiered],
["gemini-3.1-pro-high", "gemini-pro-agent"],
["gemini-3.8-flash-high", "gemini-3.8-flash-high"],
["claude-sonnet-4-6", "claude-sonnet-4-6"],
["unknown-model", "unknown-model"],
]) {
test(`${requested} retains its established family mapping`, async () => {
seed("selected", [requested]);
assert.equal(await dispatch("selected", requested), expected);
});
}
for (const [label, ttl, age, expected] of [
["default boundary", undefined, 30 * 86400000, literal],
["default expired", undefined, 30 * 86400000 + 1, tiered],
["override boundary", "1000", 1000, literal],
["override expired", "1000", 1001, tiered],
["invalid override uses default", "invalid", 86400000, literal],
["nonpositive override uses default", "0", 86400000, literal],
] as const) {
test(`freshness parity: ${label}`, async () => {
const now = Date.now();
const previousNow = Date.now;
const previousTtl = process.env.OMNIROUTE_SYNCED_CATALOG_STALE_AFTER_MS;
if (ttl === undefined) delete process.env.OMNIROUTE_SYNCED_CATALOG_STALE_AFTER_MS;
else process.env.OMNIROUTE_SYNCED_CATALOG_STALE_AFTER_MS = ttl;
Date.now = () => now;
try {
seed("selected", [literal]);
getDbInstance()
.prepare("UPDATE provider_connections SET synced_models_at = ? WHERE id = ?")
.run(new Date(now - age).toISOString(), "selected");
assert.equal(await dispatch("selected"), expected);
} finally {
Date.now = previousNow;
if (previousTtl === undefined) delete process.env.OMNIROUTE_SYNCED_CATALOG_STALE_AFTER_MS;
else process.env.OMNIROUTE_SYNCED_CATALOG_STALE_AFTER_MS = previousTtl;
}
});
}
for (const credentials of [undefined, null, {}]) {
const label = credentials === undefined ? "undefined" : credentials === null ? "null" : "empty";
test(`transformRequest preserves body project with ${label} credentials`, async () => {
const body = {
project: "synthetic-project",
request: { contents: [{ role: "user", parts: [{ text: "hello" }] }] },
};
const result = await new AntigravityExecutor().transformRequest(
literal,
body,
true,
credentials
);
assert.equal(result.project, "synthetic-project");
assert.equal(result.model, tiered);
assert.equal(result.request.contents[0].parts[0].text, "hello");
});
}