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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
Merge release/v3.7.7 into prompt compression phase 1
Antigravity Assistant16f14b76a9ef
diff --cc open-sse/config/providerHeaderProfiles.tsindex c951a8407e,301053cb04..69c591652d--- a/open-sse/config/providerHeaderProfiles.ts+++ b/open-sse/config/providerHeaderProfiles.ts@@@ -50,6 -46,48 +46,50 @@@ export function getGitHubCopilotChatHea};}+ function getRuntimePlatform(): string {+ return typeof process !== "undefined" && typeof process.platform === "string"+ ? process.platform+ : "unknown";+ }++ function getRuntimeArch(): string {- return typeof process !== "undefined" && typeof process.arch === "string" ? process.arch : "unknown";++ return typeof process !== "undefined" && typeof process.arch === "string"++ ? process.arch++ : "unknown";+ }++ function getRuntimeVersion(): string {+ return typeof process !== "undefined" && typeof process.version === "string"+ ? process.version+ : "unknown";+ }++ function normalizeStainlessPlatform(platform: string = getRuntimePlatform()): string {+ const normalized = platform.toLowerCase();+ if (normalized.includes("ios")) return "iOS";+ if (normalized === "android") return "Android";+ if (normalized === "darwin") return "MacOS";+ if (normalized === "win32") return "Windows";+ if (normalized === "freebsd") return "FreeBSD";+ if (normalized === "openbsd") return "OpenBSD";+ if (normalized === "linux") return "Linux";+ return normalized ? `Other:${normalized}` : "Unknown";+ }++ function normalizeStainlessArch(arch: string = getRuntimeArch()): string {+ if (arch === "x32") return "x32";+ if (arch === "x86_64" || arch === "x64") return "x64";+ if (arch === "arm") return "arm";+ if (arch === "aarch64" || arch === "arm64") return "arm64";+ return arch ? `other:${arch}` : "unknown";+ }++ export function getQwenCliUserAgent(version = QWEN_CLI_VERSION): string {+ // Qwen Code builds this from the runtime process values. Keep it runtime-derived so+ // packaged deployments use their own platform/architecture instead of a maintainer's host.+ return `QwenCode/${version} (${getRuntimePlatform()}; ${getRuntimeArch()})`;+ }+export function getGitHubCopilotInternalUserHeaders(authorization: string): Record<string, string> {return {Authorization: authorization,diff --cc open-sse/handlers/chatCore.tsindex d3715b718b,9317c55d98..cf9bd81634--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@@ -1220,37 -1560,7 +1560,38 @@@ export async function handleChatCore(const allMessages =body?.messages || body?.input || body?.contents || body?.request?.contents || [];if (body && Array.isArray(allMessages) && allMessages.length > 0) {-- const estimatedTokens = estimateTokens(JSON.stringify(allMessages));++ let estimatedTokens = estimateTokens(JSON.stringify(allMessages));++ // --- Modular Compression Pipeline (Phase 1: Lite mode) ---+ // Runs BEFORE the existing reactive compressContext() to proactively reduce tokens.+ try {- const { getCompressionSettings } = await import("../../src/lib/db/compression");++ const { getCompressionSettings } = await import("../../src/lib/db/compression.ts");+ const { selectCompressionStrategy, applyCompression } =- await import("../services/compression/strategySelector");- const { trackCompressionStats } = await import("../services/compression/stats");++ await import("../services/compression/strategySelector.ts");++ const { trackCompressionStats } = await import("../services/compression/stats.ts");+ const config = await getCompressionSettings();+ const mode = selectCompressionStrategy(config, comboName ?? null, estimatedTokens);+ if (mode !== "off") {+ const result = applyCompression(body, mode, { model: effectiveModel });+ if (result.compressed && result.stats) {+ body = result.body as typeof body;++ estimatedTokens = result.stats.compressedTokens;+ trackCompressionStats(result.stats);+ log?.info?.(+ "COMPRESSION",+ `Prompt compressed (${mode}): ${result.stats.originalTokens} -> ${result.stats.compressedTokens} tokens (${result.stats.savingsPercent}% saved, techniques: ${result.stats.techniquesUsed.join(",")})`+ );+ }+ }+ } catch (err) {+ log?.warn?.(+ "COMPRESSION",+ "Compression pipeline error (non-fatal): " ++ (err instanceof Error ? err.message : String(err))+ );+ }+ // --- End Modular Compression Pipeline ---+let contextLimit = getTokenLimit(provider, effectiveModel);if (isCombo && comboName) {diff --cc open-sse/services/chatgptImageCache.tsindex 0000000000,77f6759182..e6b5f8b874mode 000000,100644..100644--- a/open-sse/services/chatgptImageCache.ts+++ b/open-sse/services/chatgptImageCache.ts@@@ -1,0 -1,148 +1,143 @@@+ /**+ * In-memory cache for ChatGPT-generated images so we can serve them via a+ * regular HTTP URL instead of inlining megabytes of base64 into SSE deltas.+ *+ * Why: chatgpt.com's `image_asset_pointer` resolves to a session-signed+ * `estuary/content` URL that 403s for any anonymous client. We have to+ * download the bytes server-side (with the user's session) and re-serve+ * them. Streaming the raw base64 back through SSE works but Open WebUI's+ * progressive markdown renderer displays each chunk as text mid-stream —+ * the user sees ~3 MB of base64 scroll past before the final `)` arrives+ * and the renderer recognizes it as an image. Hosting the image on a+ * regular URL avoids that entirely: we emit a tiny ``+ * markdown delta and the browser fetches the image normally.+ *+ * The cache is in-memory only, with a short TTL — these URLs are single-use+ * artifacts of one chat turn, not persistent assets. If the user reloads+ * the conversation in a few hours the URLs will 404; that's expected.+ */++ import { createHash, randomUUID } from "node:crypto";++ interface CachedImage {+ bytes: Buffer;+ mime: string;+ expiresAt: number;+ context?: ChatGptImageConversationContext;+ /** sha256(bytes) — used by /v1/images/edits to correlate an uploaded+ * image (Open WebUI re-uploads the bytes via multipart) back to the+ * conversation context we cached when the image was first generated. */+ bytesSha256: string;+ }++ const cache = new Map<string, CachedImage>();+ let cacheBytes = 0;+ const DEFAULT_TTL_MS = 30 * 60 * 1000;+ const MAX_ENTRIES = 200;+ // Per-entry images cap at 8 MB (enforced upstream in the executor) so 32 MB+ // covers ~4 large images. The byte cap matters more than entry count: a hot+ // loop of 8 MB images would otherwise pin 1.6 GB of RSS before count+ // eviction kicked in. Tune via OMNIROUTE_CGPT_WEB_IMAGE_CACHE_MAX_MB.+ const DEFAULT_MAX_BYTES = 256 * 1024 * 1024;++ function configuredMaxBytes(): number {+ const raw = Number(process.env.OMNIROUTE_CGPT_WEB_IMAGE_CACHE_MAX_MB);+ if (!Number.isFinite(raw) || raw <= 0) return DEFAULT_MAX_BYTES;+ return Math.floor(raw * 1024 * 1024);+ }++ export interface ChatGptImageConversationContext {+ conversationId: string;+ parentMessageId: string;+ }++ function deleteEntry(id: string): void {+ const entry = cache.get(id);+ if (!entry) return;+ cacheBytes -= entry.bytes.length;+ cache.delete(id);+ }++ function evictExpired(now = Date.now()): void {+ for (const [id, entry] of cache) {+ if (now >= entry.expiresAt) deleteEntry(id);+ }+ }++ function evictUntilWithinLimits(maxBytes: number, incomingBytes: number): void {+ // Drop oldest until both the entry-count and total-byte caps are satisfied.+ // Map iteration is insertion-ordered so the first key is the oldest entry.- while (- (cache.size >= MAX_ENTRIES || cacheBytes + incomingBytes > maxBytes) &&- cache.size > 0- ) {++ while ((cache.size >= MAX_ENTRIES || cacheBytes + incomingBytes > maxBytes) && cache.size > 0) {+ const firstKey = cache.keys().next().value;+ if (!firstKey) break;+ deleteEntry(firstKey);+ }+ }++ export function storeChatGptImage(+ bytes: Buffer,+ mime: string,+ ttlMs = DEFAULT_TTL_MS,+ context?: ChatGptImageConversationContext+ ): string {+ evictExpired();+ evictUntilWithinLimits(configuredMaxBytes(), bytes.length);+ const id = randomUUID().replace(/-/g, "");+ const bytesSha256 = createHash("sha256").update(bytes).digest("hex");+ cache.set(id, {+ bytes,+ mime,+ expiresAt: Date.now() + ttlMs,+ context,+ bytesSha256,+ });+ cacheBytes += bytes.length;+ return id;+ }++ export function getChatGptImage(id: string): CachedImage | null {+ evictExpired();+ const entry = cache.get(id);+ if (!entry) return null;+ if (Date.now() >= entry.expiresAt) {+ deleteEntry(id);+ return null;+ }+ return entry;+ }++ export function getChatGptImageConversationContext(+ id: string+ ): ChatGptImageConversationContext | null {+ return getChatGptImage(id)?.context ?? null;+ }++ /**+ * Look up a cached entry by sha256(bytes). Used by /v1/images/edits to+ * correlate Open WebUI's re-uploaded image back to the conversation+ * context we cached at generation time, so the executor can continue the+ * saved chatgpt.com conversation node and actually edit the image instead+ * of generating an unrelated one from scratch.+ */-export function findChatGptImageBySha256(- hash: string-): { id: string; entry: CachedImage } | null {++export function findChatGptImageBySha256(hash: string): { id: string; entry: CachedImage } | null {+ evictExpired();+ const target = hash.toLowerCase();+ for (const [id, entry] of cache.entries()) {+ if (entry.bytesSha256 === target) {+ if (Date.now() < entry.expiresAt) return { id, entry };+ deleteEntry(id);+ }+ }+ return null;+ }++ /** Test-only: clear the cache between tests. */+ export function __resetChatGptImageCacheForTesting(): void {+ cache.clear();+ cacheBytes = 0;+ }++ /** Test-only: peek at current resident-byte total. */+ export function __getChatGptImageCacheBytesForTesting(): number {+ return cacheBytes;+ }diff --cc open-sse/services/usage.tsindex 94a51767b6,527774b13c..8c5ef39627--- a/open-sse/services/usage.ts+++ b/open-sse/services/usage.ts@@@ -815,6 -1206,80 +1206,84 @@@ function getGeminiCliPlanLabel(subscrip// Key: truncated accessToken → { data, fetchedAt }const _antigravitySubCache = new Map();const ANTIGRAVITY_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes+ const ANTIGRAVITY_MODELS_CACHE_TTL_MS = 60 * 1000;+ const ANTIGRAVITY_CREDIT_PROBE_TTL_MS = 5 * 60 * 1000;+ const _antigravityAvailableModelsCache = new Map<string, { data: unknown; fetchedAt: number }>();+ const _antigravityAvailableModelsInflight = new Map<string, Promise<unknown>>();+ const _antigravityCreditProbeCache = new Map<string, { data: number | null; fetchedAt: number }>();+ const _antigravityCreditProbeInflight = new Map<string, Promise<number | null>>();++ interface AntigravityUsageOptions {+ forceRefresh?: boolean;+ }++ function buildAntigravityUsageCacheKey(accessToken: string, projectId?: string | null): string {+ return `${accessToken.substring(0, 16)}:${projectId || "default"}`;+ }++ async function fetchAntigravityAvailableModelsCached(+ accessToken: string,+ projectId?: string | null,+ options: AntigravityUsageOptions = {}+ ): Promise<unknown> {+ if (!accessToken) throw new Error("Access token is required");++ const cacheKey = buildAntigravityUsageCacheKey(accessToken, projectId);+ const cached = _antigravityAvailableModelsCache.get(cacheKey);- if (!options.forceRefresh && cached && Date.now() - cached.fetchedAt < ANTIGRAVITY_MODELS_CACHE_TTL_MS) {++ if (++ !options.forceRefresh &&++ cached &&++ Date.now() - cached.fetchedAt < ANTIGRAVITY_MODELS_CACHE_TTL_MS++ ) {+ return cached.data;+ }++ const inflight = _antigravityAvailableModelsInflight.get(cacheKey);+ if (inflight) return inflight;++ const promise = (async () => {+ let response: Response | null = null;+ let lastError: Error | null = null;++ for (const quotaApiUrl of ANTIGRAVITY_CONFIG.quotaApiUrls) {+ try {+ response = await fetch(quotaApiUrl, {+ method: "POST",+ headers: getAntigravityHeaders("fetchAvailableModels", accessToken),+ body: JSON.stringify(projectId ? { project: projectId } : {}),+ signal: AbortSignal.timeout(10000),+ });++ if (response.ok || response.status === 401 || response.status === 403) {+ break;+ }+ } catch (error) {+ lastError = error as Error;+ }+ }++ if (!response) {+ throw lastError || new Error("Antigravity API unavailable");+ }++ if (response.status === 403) {+ return { __antigravityForbidden: true };+ }++ if (!response.ok) {+ throw new Error(`Antigravity API error: ${response.status}`);+ }++ const data = await response.json();+ _antigravityAvailableModelsCache.set(cacheKey, { data, fetchedAt: Date.now() });+ return data;+ })().finally(() => {+ _antigravityAvailableModelsInflight.delete(cacheKey);+ });++ _antigravityAvailableModelsInflight.set(cacheKey, promise);+ return promise;+ }/*** Map raw loadCodeAssist tier data to short display labels.@@@ -887,6 -1352,40 +1356,46 @@@ function getAntigravityPlanLabel(subscr* Returns the credit balance, or null if the probe failed.*/async function probeAntigravityCreditBalance(+ accessToken: string,+ accountId: string,+ projectId?: string | null,+ options: AntigravityUsageOptions = {}+ ): Promise<number | null> {+ if (!accessToken) return null;++ const cacheKey = buildAntigravityUsageCacheKey(accessToken, projectId || accountId);+ const cached = _antigravityCreditProbeCache.get(cacheKey);- if (!options.forceRefresh && cached && Date.now() - cached.fetchedAt < ANTIGRAVITY_CREDIT_PROBE_TTL_MS) {++ if (++ !options.forceRefresh &&++ cached &&++ Date.now() - cached.fetchedAt < ANTIGRAVITY_CREDIT_PROBE_TTL_MS++ ) {+ return cached.data;+ }++ const inflight = _antigravityCreditProbeInflight.get(cacheKey);+ if (inflight) return inflight;+- const promise = probeAntigravityCreditBalanceUncached(accessToken, accountId, projectId).then(- (data) => {- _antigravityCreditProbeCache.set(cacheKey, { data, fetchedAt: Date.now() });- return data;- },- (error) => {- _antigravityCreditProbeCache.set(cacheKey, { data: null, fetchedAt: Date.now() });- throw error;- }- ).finally(() => {- _antigravityCreditProbeInflight.delete(cacheKey);- });++ const promise = probeAntigravityCreditBalanceUncached(accessToken, accountId, projectId)++ .then(++ (data) => {++ _antigravityCreditProbeCache.set(cacheKey, { data, fetchedAt: Date.now() });++ return data;++ },++ (error) => {++ _antigravityCreditProbeCache.set(cacheKey, { data: null, fetchedAt: Date.now() });++ throw error;++ }++ )++ .finally(() => {++ _antigravityCreditProbeInflight.delete(cacheKey);++ });++ _antigravityCreditProbeInflight.set(cacheKey, promise);+ return promise;+ }++ async function probeAntigravityCreditBalanceUncached(accessToken: string,accountId: string,projectId?: string | null@@@ -996,45 -1500,15 +1510,20 @@@ async function getAntigravityUsage// If no cached balance and credits mode is enabled, fire a minimal probeconst creditsMode = getCreditsMode();- if (creditBalance === null && creditsMode !== "off") {- creditBalance = await probeAntigravityCreditBalance(accessToken, accountId, projectId);- }-- // Fetch model list with quota info from fetchAvailableModels- let response: Response | null = null;- let lastError: Error | null = null;-- for (const quotaApiUrl of ANTIGRAVITY_CONFIG.quotaApiUrls) {- try {- response = await fetch(quotaApiUrl, {- method: "POST",- headers: getAntigravityHeaders("fetchAvailableModels", accessToken),- body: JSON.stringify(projectId ? { project: projectId } : {}),- signal: AbortSignal.timeout(10000),- });-- if (response.ok || response.status === 401 || response.status === 403) {- break;- }- } catch (error) {- lastError = error as Error;- }- }-- if (!response) {- throw lastError || new Error("Antigravity API unavailable");+ if ((options.forceRefresh || creditBalance === null) && creditsMode !== "off") {- creditBalance = await probeAntigravityCreditBalance(accessToken, accountId, projectId, options);++ creditBalance = await probeAntigravityCreditBalance(++ accessToken,++ accountId,++ projectId,++ options++ );}- if (response.status === 403) {+ const data = await fetchAntigravityAvailableModelsCached(accessToken, projectId, options);+ const dataObj = toRecord(data);+ if (dataObj.__antigravityForbidden === true) {return { message: "Antigravity access forbidden. Check subscription." };}-- if (!response.ok) {- throw new Error(`Antigravity API error: ${response.status}`);- }-- const data = await response.json();- const dataObj = toRecord(data);const modelEntries = toRecord(dataObj.models);const quotas: Record<string, UsageQuota> = {};diff --cc src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsxindex a71b38a258,fff2b31ec3..e2c71e54d6--- a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx+++ b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx@@@ -183,15 -183,15 +183,12 @@@ export default function ApiManagerPageCfor (const key of apiKeys) {// Match analytics entry by key name (reliable across both systems)-- const analyticsMatch = byApiKey.find(-- (entry: any) => entry.apiKeyName === key.name-- );++ const analyticsMatch = byApiKey.find((entry: any) => entry.apiKeyName === key.name);// The call-logs endpoint returns entries sorted by timestamp DESC,// so the first match is the most recent one.-- const lastUsed = (logs || []).find(-- (log: any) => log.apiKeyName === key.name-- )?.timestamp || null;++ const lastUsed =++ (logs || []).find((log: any) => log.apiKeyName === key.name)?.timestamp || null;stats[key.id] = {totalRequests: analyticsMatch?.requests ?? 0,diff --cc src/app/api/auth/login/route.tsindex 8fda3a2072,b5dbf270d0..396fdc63da--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@@ -10,6 -10,11 +10,7 @@@ import} from "@/lib/auth/managementPassword";import { loginSchema } from "@/shared/validation/schemas";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";-import {- checkLoginGuard,- clearLoginAttempts,- recordLoginFailure,-} from "@/server/auth/loginGuard";++import { checkLoginGuard, clearLoginAttempts, recordLoginFailure } from "@/server/auth/loginGuard";// SECURITY: No hardcoded fallback — JWT_SECRET must be configured.if (!process.env.JWT_SECRET) {diff --cc src/app/api/providers/[id]/models/route.tsindex 5503b047cd,124c32ee4b..61dfe76020--- a/src/app/api/providers/[id]/models/route.ts+++ b/src/app/api/providers/[id]/models/route.ts@@@ -27,6 -65,8 +65,11 @@@ importtype JsonRecord = Record<string, unknown>;-const antigravityDiscoveryInflight = new Map<string, Promise<Array<{ id: string; name: string }>>>();++const antigravityDiscoveryInflight = new Map<++ string,++ Promise<Array<{ id: string; name: string }>>++>();+function asRecord(value: unknown): JsonRecord {return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};}@@@ -691,44 -1636,14 +1639,18 @@@ export async function GET});}- await resolveAntigravityVersion();-- for (const discoveryUrl of discoveryUrls) {- try {- const response = await safeOutboundFetch(discoveryUrl, {- ...SAFE_OUTBOUND_FETCH_PRESETS.modelsDiscovery,- guard: getProviderOutboundGuard(),- proxyConfig: proxy,- method: "POST",- headers: getAntigravityHeaders("models", accessToken),- body: JSON.stringify({}),- });-- if (!response.ok) {- const errorText = await response.text();- console.warn(- `[models] antigravity discovery failed at ${discoveryUrl} (${response.status}): ${errorText}`- );- continue;- }-- const remoteModels = normalizeAntigravityModelsResponse(await response.json()).map(- mapAntigravityModelForClient- );- if (remoteModels.length > 0) {- return buildResponse({- provider,- connectionId,- models: remoteModels,- source: "api",- });- }- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- console.warn(`[models] antigravity discovery threw for ${discoveryUrl}: ${message}`);- }- const remoteModels = await fetchAntigravityDiscoveryModelsCached(accessToken, connectionId, proxy);++ const remoteModels = await fetchAntigravityDiscoveryModelsCached(++ accessToken,++ connectionId,++ proxy++ );+ if (remoteModels.length > 0) {+ return buildApiDiscoveryResponse(remoteModels);}+ const fallback = buildDiscoveryFallbackResponse();+ if (fallback) return fallback;+return buildResponse({provider,connectionId,diff --cc src/app/api/usage/analytics/route.tsindex 57b2aeb69c,1d14c1e14d..2057c7bf43--- a/src/app/api/usage/analytics/route.ts+++ b/src/app/api/usage/analytics/route.ts@@@ -36,79 -126,691 +126,718 @@@ export async function GET(request: Requtry {const { searchParams } = new URL(request.url);const range = searchParams.get("range") || "30d";+ const startDate = searchParams.get("startDate") || undefined;+ const endDate = searchParams.get("endDate") || undefined;+ const apiKeyIdsParam = searchParams.get("apiKeyIds") || "";+ const apiKeyIds = apiKeyIdsParam ? apiKeyIdsParam.split(",").filter(Boolean) : [];++ const sinceIso = startDate || getRangeStartIso(range);+ const untilIso = endDate || null;+ const presetsParam = searchParams.get("presets");- // Cap history load to last 365 days — the heatmap never looks beyond that,- // and all named ranges (1d/7d/30d/90d/ytd) fall within this window.- const heatmapSince = new Date();- heatmapSince.setDate(heatmapSince.getDate() - 365);- const db = await getUsageDb(heatmapSince.toISOString());- const history = db.data.history || [];+ const db = getDbInstance();- // Build connection map for account names- const { getProviderConnections } = await import("@/lib/localDb");- const connectionMap: Record<string, string> = {};+ // ── Enrich entries with missing apiKeyName ──────────────────────────try {- const connections = await getProviderConnections();- for (const connRaw of connections as unknown[]) {- const conn =- connRaw && typeof connRaw === "object" && !Array.isArray(connRaw)- ? (connRaw as Record<string, unknown>)- : {};- const connectionId =- typeof conn.id === "string" && conn.id.trim().length > 0 ? conn.id : null;- if (!connectionId) continue;-- const name =- (typeof conn.name === "string" && conn.name.trim()) ||- (typeof conn.email === "string" && conn.email.trim()) ||- connectionId;- connectionMap[connectionId] = name;+ // Only run enrichment if there are actually NULL entries- const hasNull = db.prepare("SELECT 1 FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL LIMIT 1").get();++ const hasNull = db++ .prepare(++ "SELECT 1 FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL LIMIT 1"++ )++ .get();+ if (hasNull) {+ // Step 1: dominant key per connectionId from existing usage data- db.prepare(`++ db.prepare(++ `+ UPDATE usage_history+ SET+ api_key_name = (+ SELECT uh2.api_key_name+ FROM usage_history AS uh2+ WHERE uh2.connection_id = usage_history.connection_id+ AND uh2.api_key_name IS NOT NULL AND uh2.api_key_name != ''+ GROUP BY uh2.api_key_name+ ORDER BY COUNT(*) DESC+ LIMIT 1+ ),+ api_key_id = COALESCE(api_key_id, (+ SELECT uh2.api_key_id+ FROM usage_history AS uh2+ WHERE uh2.connection_id = usage_history.connection_id+ AND uh2.api_key_name IS NOT NULL AND uh2.api_key_name != ''+ GROUP BY uh2.api_key_name+ ORDER BY COUNT(*) DESC+ LIMIT 1+ ))+ WHERE (api_key_name IS NULL OR api_key_name = '')+ AND connection_id IS NOT NULL+ AND EXISTS (+ SELECT 1 FROM usage_history AS uh3+ WHERE uh3.connection_id = usage_history.connection_id+ AND uh3.api_key_name IS NOT NULL AND uh3.api_key_name != ''+ )- `).run();++ `++ ).run();++ // Step 2 & 3: For still unresolved connections, check apiKeys config- const stillNull = db.prepare("SELECT DISTINCT connection_id FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL").all();++ const stillNull = db++ .prepare(++ "SELECT DISTINCT connection_id FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL"++ )++ .all();+ if (stillNull.length > 0) {+ const { getApiKeys } = await import("@/lib/localDb");+ const apiKeys = (await getApiKeys()) as any[];-- const updateStmt = db.prepare("UPDATE usage_history SET api_key_name = ?, api_key_id = ? WHERE connection_id = ? AND (api_key_name IS NULL OR api_key_name = '')");++++ const updateStmt = db.prepare(++ "UPDATE usage_history SET api_key_name = ?, api_key_id = ? WHERE connection_id = ? AND (api_key_name IS NULL OR api_key_name = '')"++ );+ const updateMany = db.transaction((updates: any[]) => {+ for (const u of updates) updateStmt.run(u.name, u.id, u.cid);+ });-+++ const updates = [];+ const orphanIds = new Set(stillNull.map((r: any) => r.connection_id));-+++ for (const ak of apiKeys) {+ const allowed = Array.isArray(ak.allowedConnections) ? ak.allowedConnections : [];+ const keyName = ak.name || ak.id;+ const keyId = ak.id || null;+ for (const cid of allowed) {+ if (typeof cid === "string" && orphanIds.has(cid)) {+ updates.push({ name: keyName, id: keyId, cid });+ orphanIds.delete(cid);+ }+ }+ }-+++ if (orphanIds.size > 0) {+ const unrestrictedKeys = apiKeys.filter(- (ak: any) => !Array.isArray(ak.allowedConnections) || ak.allowedConnections.length === 0++ (ak: any) =>++ !Array.isArray(ak.allowedConnections) || ak.allowedConnections.length === 0+ );+ if (unrestrictedKeys.length > 0) {+ let bestKey = unrestrictedKeys[0];+ let bestCount = -1;+ for (const uk of unrestrictedKeys) {- const countRow = db.prepare("SELECT COUNT(*) as c FROM usage_history WHERE api_key_name = ?").get(uk.name || uk.id) as any;- if (countRow.c > bestCount) { bestCount = countRow.c; bestKey = uk; }++ const countRow = db++ .prepare("SELECT COUNT(*) as c FROM usage_history WHERE api_key_name = ?")++ .get(uk.name || uk.id) as any;++ if (countRow.c > bestCount) {++ bestCount = countRow.c;++ bestKey = uk;++ }+ }+ const fallbackName = bestKey.name || bestKey.id;+ const fallbackId = bestKey.id || null;+ for (const cid of orphanIds) {+ updates.push({ name: fallbackName, id: fallbackId, cid });+ }+ }+ }-+++ if (updates.length > 0) updateMany(updates);+ }}- } catch {- /* ignore */- } catch(e) {++ } catch (e) {+ console.error("Failed to backfill missing api_key_name:", e);}- const analytics: any = await computeAnalytics(history, range, connectionMap);+ const conditions = [];+ const params: Record<string, string> = {};- // T01: fallback transparency metrics from call_logs (requested_model vs routed model).- try {- const db = getDbInstance();- const sinceIso = getRangeStartIso(range);- const whereClause = sinceIso ? "WHERE timestamp >= @since" : "";- const row = db- .prepare(- `+ if (sinceIso) {+ conditions.push("timestamp >= @since");+ params.since = sinceIso;+ }+ if (untilIso) {+ conditions.push("timestamp <= @until");+ params.until = untilIso;+ }++ let apiKeyWhere = "";+ if (apiKeyIds.length > 0) {+ const placeholders = apiKeyIds.map((_, i) => `@apiKey${i}`);+ apiKeyIds.forEach((key, i) => {+ params[`apiKey${i}`] = key;+ });+ apiKeyWhere = `(api_key_name IN (${placeholders.join(",")}) OR api_key_id IN (${placeholders.join(",")}))`;+ conditions.push(apiKeyWhere);+ }++ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";++ // Fetch pricing data for cost calculation (no rows loaded)+ const { getPricing } = await import("@/lib/db/settings");+ const pricingByProvider = (await getPricing()) as PricingByProvider;+ const { computeCostFromPricing, normalizeModelName } =+ await import("@/lib/usage/costCalculator");++ const summaryRow = db+ .prepare(+ `+ SELECT+ COUNT(*) as totalRequests,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,+ COUNT(DISTINCT model) as uniqueModels,+ COUNT(DISTINCT connection_id) as uniqueAccounts,+ COUNT(DISTINCT api_key_id) as uniqueApiKeys,+ COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests,+ COALESCE(AVG(latency_ms), 0) as avgLatencyMs,+ COALESCE(MIN(timestamp), '') as firstRequest,+ COALESCE(MAX(timestamp), '') as lastRequest+ FROM usage_history+ ${whereClause}+ `+ )+ .get(params) as Record<string, unknown>;++ const dailyRows = db+ .prepare(+ `+ SELECT+ DATE(timestamp) as date,+ COUNT(*) as requests,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens+ FROM usage_history+ ${whereClause}+ GROUP BY DATE(timestamp)+ ORDER BY date ASC+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const dailyCostRows = db+ .prepare(+ `+ SELECT+ DATE(timestamp) as date,+ provider,+ model,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens+ FROM usage_history+ ${whereClause}+ GROUP BY DATE(timestamp), provider, model+ ORDER BY date ASC+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const heatmapStart = new Date();+ heatmapStart.setUTCDate(heatmapStart.getUTCDate() - 364);+ // Custom date range might need a wider heatmap window+ if (startDate) {+ const customStart = new Date(startDate);+ if (customStart.getTime() < heatmapStart.getTime()) {+ heatmapStart.setTime(customStart.getTime());+ }+ }-+++ // Heatmap needs its own whereClause if api keys are filtered+ const heatmapConditions = ["timestamp >= @heatmapStart"];+ if (apiKeyWhere) heatmapConditions.push(apiKeyWhere);+ const heatmapParams: Record<string, string> = { heatmapStart: heatmapStart.toISOString() };+ if (apiKeyIds.length > 0) {- apiKeyIds.forEach((key, i) => { heatmapParams[`apiKey${i}`] = key; });++ apiKeyIds.forEach((key, i) => {++ heatmapParams[`apiKey${i}`] = key;++ });+ }++ const heatmapRows = db+ .prepare(+ `+ SELECT+ DATE(timestamp) as date,+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens+ FROM usage_history+ WHERE ${heatmapConditions.join(" AND ")}+ GROUP BY DATE(timestamp)+ ORDER BY date ASC+ `+ )+ .all(heatmapParams) as Array<Record<string, unknown>>;++ const modelRows = db+ .prepare(+ `+ SELECT+ model,+ provider,+ COUNT(*) as requests,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,+ COALESCE(AVG(latency_ms), 0) as avgLatencyMs,+ COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests,+ COALESCE(MAX(timestamp), '') as lastUsed+ FROM usage_history+ ${whereClause}+ GROUP BY model, provider+ ORDER BY requests DESC+ LIMIT 50+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const providerCostRows = db+ .prepare(+ `+ SELECT+ provider,+ model,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens+ FROM usage_history+ ${whereClause}+ GROUP BY provider, model+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const providerRows = db+ .prepare(+ `+ SELECT+ provider,+ COUNT(*) as requests,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,+ COALESCE(AVG(latency_ms), 0) as avgLatencyMs,+ COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests+ FROM usage_history+ ${whereClause}+ GROUP BY provider+ ORDER BY requests DESC+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const accountCostRows = db+ .prepare(+ `+ SELECT+ connection_id as account,+ provider,+ model,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens+ FROM usage_history+ ${whereClause}+ GROUP BY connection_id, provider, model+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const accountRows = db+ .prepare(+ `+ SELECT+ connection_id as account,+ COUNT(*) as requests,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,+ COALESCE(AVG(latency_ms), 0) as avgLatencyMs,+ COALESCE(MAX(timestamp), '') as lastUsed+ FROM usage_history+ ${whereClause}+ GROUP BY connection_id+ ORDER BY requests DESC+ LIMIT 50+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const apiKeyWhereClause = appendWhereCondition(+ whereClause,+ "(api_key_id IS NOT NULL AND api_key_id != '') OR (api_key_name IS NOT NULL AND api_key_name != '')"+ );+ const apiKeyRows = db+ .prepare(+ `+ SELECT+ api_key_id as apiKeyId,+ COALESCE(NULLIF(api_key_name, ''), NULLIF(api_key_id, ''), 'Unknown API key') as apiKeyName,+ provider,+ model,+ COUNT(*) as requests,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens+ FROM usage_history+ ${apiKeyWhereClause}+ GROUP BY api_key_id, api_key_name, provider, model+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const weeklyRows = db+ .prepare(+ `+ SELECT+ dayOfWeek,+ COUNT(*) as days,+ COALESCE(SUM(requests), 0) as requests,+ COALESCE(SUM(totalTokens), 0) as totalTokens+ FROM (SELECT- COUNT(*) as total,- SUM(CASE WHEN requested_model IS NOT NULL AND requested_model != '' THEN 1 ELSE 0 END) as with_requested,- SUM(CASE- WHEN requested_model IS NOT NULL- AND requested_model != ''- AND model IS NOT NULL- AND requested_model != model- THEN 1 ELSE 0 END- ) as fallbacks- FROM call_logs+ DATE(timestamp) as date,+ strftime('%w', timestamp) as dayOfWeek,+ COUNT(*) as requests,+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens+ FROM usage_history${whereClause}- `+ GROUP BY DATE(timestamp), strftime('%w', timestamp))- .get(sinceIso ? { since: sinceIso } : {}) as- | { total?: number; with_requested?: number; fallbacks?: number }- | undefined;-- const total = Number(row?.total || 0);- const withRequested = Number(row?.with_requested || 0);- const fallbackCount = Number(row?.fallbacks || 0);-- analytics.summary.fallbackCount = fallbackCount;- analytics.summary.fallbackRatePct =- withRequested > 0 ? Number(((fallbackCount / withRequested) * 100).toFixed(2)) : 0;- analytics.summary.requestedModelCoveragePct =- total > 0 ? Number(((withRequested / total) * 100).toFixed(2)) : 0;- } catch {- analytics.summary.fallbackCount = 0;- analytics.summary.fallbackRatePct = 0;- analytics.summary.requestedModelCoveragePct = 0;+ GROUP BY dayOfWeek+ ORDER BY dayOfWeek ASC+ `+ )+ .all(params) as Array<Record<string, unknown>>;++ const fallbackRow = db+ .prepare(+ `+ SELECT+ COUNT(*) as total,+ SUM(CASE WHEN requested_model IS NOT NULL AND requested_model != '' THEN 1 ELSE 0 END) as with_requested,+ SUM(CASE+ WHEN requested_model IS NOT NULL+ AND requested_model != ''+ AND model IS NOT NULL+ AND requested_model != model+ THEN 1 ELSE 0 END+ ) as fallbacks+ FROM call_logs+ ${whereClause}+ `+ )+ .get(params) as Record<string, unknown>;++ const summary = {+ totalRequests: Number(summaryRow?.totalRequests || 0),+ promptTokens: Number(summaryRow?.promptTokens || 0),+ completionTokens: Number(summaryRow?.completionTokens || 0),+ totalTokens: Number(summaryRow?.totalTokens || 0),+ uniqueModels: Number(summaryRow?.uniqueModels || 0),+ uniqueAccounts: Number(summaryRow?.uniqueAccounts || 0),+ uniqueApiKeys: Number(summaryRow?.uniqueApiKeys || 0),+ successfulRequests: Number(summaryRow?.successfulRequests || 0),+ successRatePct:+ Number(summaryRow?.totalRequests || 0) > 0+ ? Number(+ (+ (Number(summaryRow?.successfulRequests || 0) /+ Number(summaryRow?.totalRequests || 1)) *+ 100+ ).toFixed(2)+ )+ : 0,+ avgLatencyMs: Math.round(Number(summaryRow?.avgLatencyMs || 0)),- totalCost: 0,++ totalCost: 0,+ firstRequest: summaryRow?.firstRequest || "",+ lastRequest: summaryRow?.lastRequest || "",+ fallbackCount: Number(fallbackRow?.fallbacks || 0),+ fallbackRatePct:+ Number(fallbackRow?.with_requested || 0) > 0+ ? Number(+ (+ (Number(fallbackRow?.fallbacks || 0) / Number(fallbackRow?.with_requested || 1)) *+ 100+ ).toFixed(2)+ )+ : 0,+ requestedModelCoveragePct:+ Number(fallbackRow?.total || 0) > 0+ ? Number(+ (+ (Number(fallbackRow?.with_requested || 0) / Number(fallbackRow?.total || 1)) *+ 100+ ).toFixed(2)+ )+ : 0,+ streak: 0,+ };++ const dailyCostByDate = new Map<string, number>();+ for (const row of dailyCostRows) {+ const date = toStringValue(row.date);+ if (!date) continue;+ const cost = computeUsageRowCost(+ row,+ pricingByProvider,+ normalizeModelName,+ computeCostFromPricing+ );+ dailyCostByDate.set(date, (dailyCostByDate.get(date) || 0) + cost);+ }++ const dailyTrend = dailyRows.map((row) => ({+ date: row.date,+ requests: Number(row.requests),+ promptTokens: Number(row.promptTokens),+ completionTokens: Number(row.completionTokens),+ totalTokens: Number(row.totalTokens),+ cost: roundCost(dailyCostByDate.get(toStringValue(row.date)) || 0),+ }));++ const activityMap: Record<string, number> = {};+ for (const row of heatmapRows) {+ activityMap[row.date as string] = Number(row.totalTokens);+ }+ summary.streak = computeActivityStreak(activityMap);++ const byModel = modelRows.map((row) => {+ const model = row.model as string;+ const provider = row.provider as string;+ const short = shortModelName(model);+ const tokens = {+ input: Number(row.promptTokens) || 0,+ output: Number(row.completionTokens) || 0,+ };+ const cost = computeUsageRowCost(+ row,+ pricingByProvider,+ normalizeModelName,+ computeCostFromPricing+ );+ return {+ model: short,+ provider,+ rawModel: model,+ requests: Number(row.requests),+ promptTokens: tokens.input,+ completionTokens: tokens.output,+ totalTokens: Number(row.totalTokens),+ avgLatencyMs: Math.round(Number(row.avgLatencyMs)),+ successRatePct:+ Number(row.requests) > 0+ ? Number((Number(row.successfulRequests) / Number(row.requests)) * 100).toFixed(2)+ : 0,+ lastUsed: row.lastUsed,+ cost: roundCost(cost),+ };+ });++ const totalCost = Array.from(dailyCostByDate.values()).reduce((sum, cost) => sum + cost, 0);+ summary.totalCost = roundCost(totalCost);++ const providerCostByProvider = new Map<string, number>();+ for (const row of providerCostRows) {+ const provider = toStringValue(row.provider);+ if (!provider) continue;+ const cost = computeUsageRowCost(+ row,+ pricingByProvider,+ normalizeModelName,+ computeCostFromPricing+ );+ providerCostByProvider.set(provider, (providerCostByProvider.get(provider) || 0) + cost);+ }++ const byProvider = providerRows.map((row) => ({+ provider: row.provider,+ requests: Number(row.requests),+ promptTokens: Number(row.promptTokens),+ completionTokens: Number(row.completionTokens),+ totalTokens: Number(row.totalTokens),+ avgLatencyMs: Math.round(Number(row.avgLatencyMs)),+ successRatePct:+ Number(row.requests) > 0+ ? Number((Number(row.successfulRequests) / Number(row.requests)) * 100).toFixed(2)+ : 0,+ cost: roundCost(providerCostByProvider.get(toStringValue(row.provider)) || 0),+ }));++ const accountCostByAccount = new Map<string, number>();+ for (const row of accountCostRows) {+ const account = toStringValue(row.account, "unknown");+ const cost = computeUsageRowCost(+ row,+ pricingByProvider,+ normalizeModelName,+ computeCostFromPricing+ );+ accountCostByAccount.set(account, (accountCostByAccount.get(account) || 0) + cost);+ }++ const byAccount = accountRows.map((row) => ({+ account: toStringValue(row.account, "unknown"),+ requests: Number(row.requests),+ promptTokens: Number(row.promptTokens),+ completionTokens: Number(row.completionTokens),+ totalTokens: Number(row.totalTokens),+ avgLatencyMs: Math.round(Number(row.avgLatencyMs)),+ lastUsed: row.lastUsed,+ cost: roundCost(accountCostByAccount.get(toStringValue(row.account, "unknown")) || 0),+ }));++ const apiKeyMap = new Map<+ string,+ {+ apiKey: string;+ apiKeyId: string | null;+ apiKeyName: string;+ requests: number;+ promptTokens: number;+ completionTokens: number;+ totalTokens: number;+ cost: number;+ }+ >();+ for (const row of apiKeyRows) {+ const apiKeyId = toStringValue(row.apiKeyId);+ const apiKeyName = toStringValue(row.apiKeyName, apiKeyId || "Unknown API key");+ const key = `${apiKeyId || "unknown"}::${apiKeyName}`;+ const existing = apiKeyMap.get(key) || {+ apiKey: apiKeyId && apiKeyName !== apiKeyId ? `${apiKeyName} (${apiKeyId})` : apiKeyName,+ apiKeyId: apiKeyId || null,+ apiKeyName,+ requests: 0,+ promptTokens: 0,+ completionTokens: 0,+ totalTokens: 0,+ cost: 0,+ };++ existing.requests += Number(row.requests);+ existing.promptTokens += Number(row.promptTokens);+ existing.completionTokens += Number(row.completionTokens);+ existing.totalTokens += Number(row.totalTokens);+ existing.cost += computeUsageRowCost(+ row,+ pricingByProvider,+ normalizeModelName,+ computeCostFromPricing+ );+ apiKeyMap.set(key, existing);+ }+ const byApiKey = Array.from(apiKeyMap.values())+ .map((row) => ({ ...row, cost: roundCost(row.cost) }))+ .sort((left, right) => right.cost - left.cost);++ const weeklyTokens = [0, 0, 0, 0, 0, 0, 0];+ const weeklyCounts = [0, 0, 0, 0, 0, 0, 0];+ const weeklyPattern = WEEKDAY_LABELS.map((day) => ({+ day,+ avgTokens: 0,+ totalTokens: 0,+ }));+ for (const row of weeklyRows) {+ const dayIdx = Number(row.dayOfWeek);+ if (dayIdx >= 0 && dayIdx <= 6) {+ const totalTokens = Number(row.totalTokens);+ const days = Number(row.days);+ weeklyTokens[dayIdx] = totalTokens;+ weeklyCounts[dayIdx] = Number(row.requests);+ weeklyPattern[dayIdx] = {+ day: WEEKDAY_LABELS[dayIdx],+ avgTokens: days > 0 ? Math.round(totalTokens / days) : 0,+ totalTokens,+ };+ }+ }++ const analytics = {+ summary,+ dailyTrend,+ activityMap,+ byModel,+ byProvider,+ byApiKey,+ byAccount,+ weeklyPattern,+ weeklyTokens,+ weeklyCounts,+ range,+ } as any;++ if (presetsParam) {+ const allowedRanges = new Set(["1d", "7d", "30d", "90d", "ytd", "all"]);+ const presetRanges = presetsParam+ .split(",")+ .map((preset) => preset.trim())+ .filter((preset) => allowedRanges.has(preset));+ const presetSummaries: Record<string, { totalCost: number }> = {};++ for (const presetRange of presetRanges) {+ if (presetRange === range) {+ presetSummaries[presetRange] = {+ totalCost: Number(analytics.summary?.totalCost || 0),+ };+ continue;+ }++ const presetSinceIso = getRangeStartIso(presetRange);+ const presetConditions = [];+ const presetParams: Record<string, string> = {};- if (presetSinceIso) { presetConditions.push("timestamp >= @presetSince"); presetParams.presetSince = presetSinceIso; }- if (apiKeyWhere) { presetConditions.push(apiKeyWhere); Object.assign(presetParams, params); }++ if (presetSinceIso) {++ presetConditions.push("timestamp >= @presetSince");++ presetParams.presetSince = presetSinceIso;++ }++ if (apiKeyWhere) {++ presetConditions.push(apiKeyWhere);++ Object.assign(presetParams, params);++ }+- const presetWhere = presetConditions.length > 0 ? `WHERE ${presetConditions.join(" AND ")}` : "";++ const presetWhere =++ presetConditions.length > 0 ? `WHERE ${presetConditions.join(" AND ")}` : "";++ const presetModelRows = db+ .prepare(+ `+ SELECT+ model,+ provider,+ COALESCE(SUM(tokens_input), 0) as promptTokens,+ COALESCE(SUM(tokens_output), 0) as completionTokens,+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens+ FROM usage_history+ ${presetWhere}+ GROUP BY model, provider+ `+ )+ .all(presetParams) as Array<Record<string, unknown>>;++ let presetTotalCost = 0;+ for (const row of presetModelRows) {+ presetTotalCost += computeUsageRowCost(+ row,+ pricingByProvider,+ normalizeModelName,+ computeCostFromPricing+ );+ }++ presetSummaries[presetRange] = {+ totalCost: roundCost(presetTotalCost),+ };+ }++ analytics.presetSummaries = presetSummaries;}return NextResponse.json(analytics);diff --cc src/lib/db/migrations/034_compression_settings.sqlindex 0000000000,0000000000..1a63062c32new file mode 100644--- /dev/null+++ b/src/lib/db/migrations/034_compression_settings.sql@@@ -1,0 -1,0 +1,10 @@@++-- 034_compression_settings.sql++-- Insert default compression settings into key_value table (namespace='compression')++-- Uses INSERT OR IGNORE so existing user settings are never overwritten by migration replay.++++INSERT OR IGNORE INTO key_value (namespace, key, value) VALUES ('compression', 'enabled', 'false');++INSERT OR IGNORE INTO key_value (namespace, key, value) VALUES ('compression', 'defaultMode', '"off"');++INSERT OR IGNORE INTO key_value (namespace, key, value) VALUES ('compression', 'autoTriggerTokens', '0');++INSERT OR IGNORE INTO key_value (namespace, key, value) VALUES ('compression', 'cacheMinutes', '5');++INSERT OR IGNORE INTO key_value (namespace, key, value) VALUES ('compression', 'preserveSystemPrompt', 'true');++INSERT OR IGNORE INTO key_value (namespace, key, value) VALUES ('compression', 'comboOverrides', '{}');diff --cc tests/unit/cli-tools.test.tsindex ae2f7e1ff6,171a0d2b46..fadd60e8a0--- a/tests/unit/cli-tools.test.ts+++ b/tests/unit/cli-tools.test.ts@@@ -2,9 -2,18 +2,16 @@@ import test from "node:test"import assert from "node:assert/strict";const { CLI_TOOLS } = await import("../../src/shared/constants/cliTools.ts");- const { CLI_COMPAT_PROVIDER_IDS } =- await import("../../src/shared/constants/cliCompatProviders.ts");+ const {+ CLI_COMPAT_PROVIDER_IDS,+ CLI_COMPAT_OMITTED_PROVIDER_IDS,+ CLI_COMPAT_TOGGLE_IDS,+ IMPLEMENTED_CLI_FINGERPRINT_PROVIDER_IDS,+ normalizeCliCompatProviderId,-} =- await import("../../src/shared/constants/cliCompatProviders.ts");++} = await import("../../src/shared/constants/cliCompatProviders.ts");const { CLI_TOOL_IDS } = await import("../../src/shared/services/cliRuntime.ts");-const { applyFingerprint, isCliCompatEnabled, setCliCompatProviders } = await import(- "../../open-sse/config/cliFingerprints.ts"-);++const { applyFingerprint, isCliCompatEnabled, setCliCompatProviders } =++ await import("../../open-sse/config/cliFingerprints.ts");test("Amp CLI is registered as a guide-based CLI tool with shorthand mapping guidance", () => {const amp = CLI_TOOLS.amp;diff --cc tests/unit/combo-stream-readiness-fallback.test.tsindex 0000000000,ed8cdc1e28..7f1122a24emode 000000,100644..100644--- a/tests/unit/combo-stream-readiness-fallback.test.ts+++ b/tests/unit/combo-stream-readiness-fallback.test.ts@@@ -1,0 -1,235 +1,228 @@@+ import test from "node:test";+ import assert from "node:assert/strict";++ import { handleComboChat } from "../../open-sse/services/combo.ts";+ import { ensureStreamReadiness } from "../../open-sse/utils/streamReadiness.ts";++ const textEncoder = new TextEncoder();++ function createLog() {+ const entries: any[] = [];+ return {+ info: (tag: any, msg: any) => entries.push({ level: "info", tag, msg }),+ warn: (tag: any, msg: any) => entries.push({ level: "warn", tag, msg }),+ error: (tag: any, msg: any) => entries.push({ level: "error", tag, msg }),+ debug: (tag: any, msg: any) => entries.push({ level: "debug", tag, msg }),+ entries,+ };+ }++ function okStreamResponse(content: string): Response {+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(+ textEncoder.encode(+ `data: ${JSON.stringify({+ choices: [{ delta: { role: "assistant", content } }],+ })}\n\n`+ )+ );+ controller.enqueue(+ textEncoder.encode(+ `data: ${JSON.stringify({+ choices: [{ delta: {}, finish_reason: "stop" }],+ })}\n\n`+ )+ );+ controller.enqueue(textEncoder.encode("data: [DONE]\n\n"));+ controller.close();+ },+ });+ return new Response(body, {+ status: 200,+ headers: { "Content-Type": "text/event-stream" },+ });+ }++ function zombieStreamResponse(): Response {+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(textEncoder.encode(": keepalive\n\n"));+ controller.enqueue(textEncoder.encode(`data: ${JSON.stringify({ type: "ping" })}\n\n`));+ // Keep the stream open without useful content, matching HTTP 200 zombie streams.+ },+ cancel() {},+ });++ return new Response(body, {+ status: 200,+ headers: { "Content-Type": "text/event-stream" },+ });+ }++ async function applyStreamReadiness(response: Response): Promise<Response> {+ const result = await ensureStreamReadiness(response, {+ timeoutMs: 10,+ provider: "glm",+ model: "zombie-model",+ log: createLog(),+ });+ return result.response;+ }++ function errorResponse(status: number, message: string): Response {- return new Response(- JSON.stringify({ error: { message, type: "upstream_error" } }),- { status, headers: { "Content-Type": "application/json" } }- );++ return new Response(JSON.stringify({ error: { message, type: "upstream_error" } }), {++ status,++ headers: { "Content-Type": "application/json" },++ });+ }++ test("combo falls back when first model returns HTTP 200 zombie SSE stream", async () => {+ const calls: string[] = [];+ const log = createLog();++ const result = await handleComboChat({+ body: {+ stream: true,+ messages: [{ role: "user", content: "hello" }],+ },+ combo: {+ name: "stream-readiness-504-fallback",+ strategy: "priority",+ models: [+ { model: "glm/zombie-model", weight: 0 },+ { model: "openai/gpt-5.4-mini", weight: 0 },+ ],+ config: { maxRetries: 0, retryDelayMs: 0 },+ },+ handleSingleModel: async (_body: any, modelStr: string) => {+ calls.push(modelStr);+ if (modelStr === "glm/zombie-model") {+ return applyStreamReadiness(zombieStreamResponse());+ }+ return okStreamResponse("fallback success");+ },+ isModelAvailable: async () => true,+ log,+ settings: null,+ allCombos: null,+ relayOptions: null as any,+ });++ assert.equal(result.ok, true, "combo should succeed via fallback after 504");+ assert.deepEqual(calls, ["glm/zombie-model", "openai/gpt-5.4-mini"]);+ assert.ok(+ log.entries.some(- (e) =>- e.level === "warn" &&- e.tag === "COMBO" &&- String(e.msg).includes("glm/zombie-model")++ (e) => e.level === "warn" && e.tag === "COMBO" && String(e.msg).includes("glm/zombie-model")+ ),+ "combo should log warning for the failed model"+ );+ });++ test("combo fails when all models return 504", async () => {+ const calls: string[] = [];+ const log = createLog();++ const result = await handleComboChat({+ body: {+ stream: true,+ messages: [{ role: "user", content: "hello" }],+ },+ combo: {+ name: "all-504-test",+ strategy: "priority",+ models: [+ { model: "glm/zombie-a", weight: 0 },+ { model: "glm/zombie-b", weight: 0 },+ ],+ config: { maxRetries: 0, retryDelayMs: 0 },+ },+ handleSingleModel: async (_body: any, modelStr: string) => {+ calls.push(modelStr);+ return applyStreamReadiness(zombieStreamResponse());+ },+ isModelAvailable: async () => true,+ log,+ settings: null,+ allCombos: null,+ relayOptions: null as any,+ });++ assert.ok(!result.ok, "combo should fail when all models return 504");+ assert.equal(result.status, 504);+ assert.equal(calls.length, 2, "combo should try both models");+ });++ test("combo retries 504 on same model before falling through (transient retry)", async () => {+ const calls: string[] = [];+ const log = createLog();++ const result = await handleComboChat({+ body: {+ stream: true,+ messages: [{ role: "user", content: "hello" }],+ },+ combo: {+ name: "retry-504-test",+ strategy: "priority",+ models: [+ { model: "glm/zombie", weight: 0 },+ { model: "openai/gpt-5.4-mini", weight: 0 },+ ],+ config: { maxRetries: 1, retryDelayMs: 0 },+ },+ handleSingleModel: async (_body: any, modelStr: string) => {+ calls.push(modelStr);+ if (modelStr === "glm/zombie") {+ return errorResponse(504, "Stream produced no useful content within 60000ms");+ }+ return okStreamResponse("fallback after retries");+ },+ isModelAvailable: async () => true,+ log,+ settings: null,+ allCombos: null,+ relayOptions: null as any,+ });++ assert.equal(result.ok, true, "combo should succeed via fallback after retries");+ const zombieCalls = calls.filter((c) => c === "glm/zombie");- assert.equal(- zombieCalls.length,- 2,- "combo should retry zombie once before falling through"- );++ assert.equal(zombieCalls.length, 2, "combo should retry zombie once before falling through");+ assert.ok(calls.includes("openai/gpt-5.4-mini"), "combo should reach fallback model");+ });++ test("combo does not retry stream readiness timeouts on the same model", async () => {+ const calls: string[] = [];+ const log = createLog();++ const result = await handleComboChat({+ body: {+ stream: true,+ messages: [{ role: "user", content: "hello" }],+ },+ combo: {+ name: "no-retry-readiness-timeout-test",+ strategy: "priority",+ models: [+ { model: "glm/zombie", weight: 0 },+ { model: "openai/gpt-5.4-mini", weight: 0 },+ ],+ config: { maxRetries: 1, retryDelayMs: 0 },+ },+ handleSingleModel: async (_body: any, modelStr: string) => {+ calls.push(modelStr);+ if (modelStr === "glm/zombie") {+ return applyStreamReadiness(zombieStreamResponse());+ }+ return okStreamResponse("fallback without same-model retry");+ },+ isModelAvailable: async () => true,+ log,+ settings: null,+ allCombos: null,+ relayOptions: null as any,+ });++ assert.equal(result.ok, true, "combo should succeed via fallback");+ assert.deepEqual(calls, ["glm/zombie", "openai/gpt-5.4-mini"]);+ });diff --cc tests/unit/compression/db.test.tsindex 134a4c19f0,0000000000..4d78a929c3mode 100644,000000..100644--- a/tests/unit/compression/db.test.ts+++ b/tests/unit/compression/db.test.ts@@@ -1,86 -1,0 +1,113 @@@- import { describe, it, beforeEach, afterEach } from "node:test";++import { describe, it, beforeEach, afterEach, after } from "node:test";+import assert from "node:assert/strict";- import {- getCompressionSettings,- updateCompressionSettings,- } from "../../../src/lib/db/compression.ts";++import fs from "node:fs";++import os from "node:os";++import path from "node:path";++++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-compression-db-"));++const ORIGINAL_DATA_DIR = process.env.DATA_DIR;++process.env.DATA_DIR = TEST_DATA_DIR;++++const core = await import("../../../src/lib/db/core.ts");++const { getCompressionSettings, updateCompressionSettings } =++ await import("../../../src/lib/db/compression.ts");++++beforeEach(() => {++ core.resetDbInstance();++ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });++ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });++});++++afterEach(() => {++ core.resetDbInstance();++});++++after(() => {++ core.resetDbInstance();++ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });++ if (ORIGINAL_DATA_DIR === undefined) {++ delete process.env.DATA_DIR;++ } else {++ process.env.DATA_DIR = ORIGINAL_DATA_DIR;++ }++});++describe("getCompressionSettings", () => {+ it("returns default settings structure", async () => {+ const settings = await getCompressionSettings();+ assert.equal(typeof settings.enabled, "boolean");+ assert.equal(typeof settings.defaultMode, "string");+ assert.equal(typeof settings.autoTriggerTokens, "number");+ assert.equal(typeof settings.cacheMinutes, "number");+ assert.equal(typeof settings.preserveSystemPrompt, "boolean");+ assert.equal(typeof settings.comboOverrides, "object");+ });++ it("has correct default values", async () => {+ const settings = await getCompressionSettings();+ assert.equal(settings.enabled, false);+ assert.equal(settings.defaultMode, "off");+ assert.equal(settings.autoTriggerTokens, 0);+ assert.equal(settings.cacheMinutes, 5);+ assert.equal(settings.preserveSystemPrompt, true);+ assert.deepEqual(settings.comboOverrides, {});+ });+});++describe("updateCompressionSettings", () => {+ it("updates enabled flag", async () => {+ await updateCompressionSettings({ enabled: true } as any);+ const settings = await getCompressionSettings();+ assert.equal(settings.enabled, true);+ // Reset+ await updateCompressionSettings({ enabled: false } as any);+ });++ it("updates defaultMode", async () => {+ await updateCompressionSettings({ defaultMode: "lite" } as any);+ const settings = await getCompressionSettings();+ assert.equal(settings.defaultMode, "lite");+ // Reset+ await updateCompressionSettings({ defaultMode: "off" } as any);+ });++ it("updates autoTriggerTokens", async () => {+ await updateCompressionSettings({ autoTriggerTokens: 5000 } as any);+ const settings = await getCompressionSettings();+ assert.equal(settings.autoTriggerTokens, 5000);+ // Reset+ await updateCompressionSettings({ autoTriggerTokens: 0 } as any);+ });++ it("updates multiple settings at once", async () => {+ await updateCompressionSettings({+ enabled: true,+ defaultMode: "lite",+ autoTriggerTokens: 1000,+ cacheMinutes: 10,+ } as any);+ const settings = await getCompressionSettings();+ assert.equal(settings.enabled, true);+ assert.equal(settings.defaultMode, "lite");+ assert.equal(settings.autoTriggerTokens, 1000);+ assert.equal(settings.cacheMinutes, 10);+ // Reset all+ await updateCompressionSettings({+ enabled: false,+ defaultMode: "off",+ autoTriggerTokens: 0,+ cacheMinutes: 5,+ } as any);+ });++ it("preserves unmodified settings", async () => {+ const before = await getCompressionSettings();+ await updateCompressionSettings({ enabled: true } as any);+ const after = await getCompressionSettings();+ assert.equal(after.enabled, true);+ assert.equal(after.defaultMode, before.defaultMode);+ assert.equal(after.cacheMinutes, before.cacheMinutes);+ // Reset+ await updateCompressionSettings({ enabled: false } as any);+ });+});diff --cc tests/unit/provider-header-profiles.test.tsindex 3b47a51cfc,4383d5a262..df7e79b340--- a/tests/unit/provider-header-profiles.test.ts+++ b/tests/unit/provider-header-profiles.test.ts@@@ -47,13 -47,16 +47,19 @@@ test("provider header profiles expose dassert.equal(refreshHeaders["Editor-Plugin-Version"], GITHUB_COPILOT_REFRESH_PLUGIN_VERSION);const qwenHeaders = getQwenOauthHeaders();- assert.equal(qwenHeaders["User-Agent"], QWEN_CLI_USER_AGENT);- assert.equal(qwenHeaders["X-Dashscope-UserAgent"], QWEN_CLI_USER_AGENT);+ assert.equal(qwenHeaders["User-Agent"], getQwenCliUserAgent());- assert.equal(qwenHeaders["User-Agent"], `QwenCode/${QWEN_CLI_VERSION} (${process.platform}; ${process.arch})`);++ assert.equal(++ qwenHeaders["User-Agent"],++ `QwenCode/${QWEN_CLI_VERSION} (${process.platform}; ${process.arch})`++ );+ assert.notEqual(qwenHeaders["User-Agent"], "QwenCode/0.15.3 (linux; x64)");+ assert.equal(qwenHeaders["X-Dashscope-UserAgent"], getQwenCliUserAgent());assert.equal(qwenHeaders["X-Stainless-Package-Version"], "5.11.0");+ assert.equal(qwenHeaders["X-Stainless-Runtime-Version"], process.version);const qoderHeaders = getQoderDashscopeCompatHeaders();- assert.equal(qoderHeaders["user-agent"], QODER_DASHSCOPE_COMPAT_USER_AGENT);- assert.equal(qoderHeaders["x-dashscope-useragent"], QODER_DASHSCOPE_COMPAT_USER_AGENT);+ assert.equal(qoderHeaders["user-agent"], getQwenCliUserAgent());+ assert.equal(qoderHeaders["x-dashscope-useragent"], getQwenCliUserAgent());const kiroHeaders = getKiroServiceHeaders("application/json");assert.equal(kiroHeaders.Accept, "application/json");diff --cc tests/unit/stream-readiness.test.tsindex 0000000000,2e429921d9..a86c37dd31mode 000000,100644..100644--- a/tests/unit/stream-readiness.test.ts+++ b/tests/unit/stream-readiness.test.ts@@@ -1,0 -1,122 +1,125 @@@+ import test from "node:test";+ import assert from "node:assert/strict";++ import {+ ensureStreamReadiness,+ hasUsefulStreamContent,+ } from "../../open-sse/utils/streamReadiness.ts";++ const encoder = new TextEncoder();++ function streamFromChunks(chunks: string[], delayMs = 0): ReadableStream<Uint8Array> {+ return new ReadableStream<Uint8Array>({+ async start(controller) {+ for (const chunk of chunks) {+ if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));+ controller.enqueue(encoder.encode(chunk));+ }+ controller.close();+ },+ });+ }++ test("hasUsefulStreamContent ignores keepalives and lifecycle-only chunks", () => {+ assert.equal(hasUsefulStreamContent(": keepalive\n\n"), false);+ assert.equal(hasUsefulStreamContent("event: ping\ndata: {}\n\n"), false);+ assert.equal(+ hasUsefulStreamContent(`data: ${JSON.stringify({ type: "response.created" })}\n\n`),+ false+ );+ assert.equal(+ hasUsefulStreamContent(+ `data: ${JSON.stringify({ choices: [{ delta: { role: "assistant" }, index: 0 }] })}\n\n`+ ),+ false+ );+ });++ test("hasUsefulStreamContent detects text, reasoning, and tool deltas", () => {+ assert.equal(+ hasUsefulStreamContent(+ `data: ${JSON.stringify({ choices: [{ delta: { content: "hello" }, index: 0 }] })}\n\n`+ ),+ true+ );+ assert.equal(+ hasUsefulStreamContent(+ `data: ${JSON.stringify({ choices: [{ delta: { content: " " }, index: 0 }] })}\n\n`+ ),+ true+ );+ assert.equal(+ hasUsefulStreamContent(+ `data: ${JSON.stringify({ choices: [{ delta: { reasoning_content: "thinking" }, index: 0 }] })}\n\n`+ ),+ true+ );+ assert.equal(+ hasUsefulStreamContent(+ `data: ${JSON.stringify({ choices: [{ delta: { tool_calls: [{ function: { name: "read" } }] }, index: 0 }] })}\n\n`+ ),+ true+ );+ assert.equal(+ hasUsefulStreamContent(+ `data: ${JSON.stringify({ type: "content_block_delta", delta: { text: "hello" } })}\n\n`+ ),+ true+ );+ assert.equal(+ hasUsefulStreamContent(+ `data: ${JSON.stringify({ type: "response.output_text.delta", delta: "hello" })}\n\n`+ ),+ true+ );+ assert.equal(+ hasUsefulStreamContent(+ `data: ${JSON.stringify({ response: { candidates: [{ content: { parts: [{ text: "hello" }] } }] } })}\n\n`+ ),+ true+ );+ });++ test("ensureStreamReadiness preserves buffered chunks when stream starts", async () => {+ const response = new Response(+ streamFromChunks([+ `data: ${JSON.stringify({ type: "response.created" })}\n\n`,+ `data: ${JSON.stringify({ choices: [{ delta: { content: "hello" }, index: 0 }] })}\n\n`,+ `data: ${JSON.stringify({ choices: [{ delta: { content: " world" }, index: 0 }] })}\n\n`,+ ]),+ { status: 200, headers: { "Content-Type": "text/event-stream" } }+ );++ const result = await ensureStreamReadiness(response, { timeoutMs: 100 });+ assert.equal(result.ok, true);+ const text = await result.response.text();+ assert.match(text, /response\.created/);+ assert.match(text, /hello/);+ assert.match(text, / world/);+ });++ test("ensureStreamReadiness returns 504 when no useful content arrives before timeout", async () => {+ const response = new Response(- streamFromChunks([": keepalive\n\n", `data: ${JSON.stringify({ type: "response.created" })}\n\n`], 20),++ streamFromChunks(++ [": keepalive\n\n", `data: ${JSON.stringify({ type: "response.created" })}\n\n`],++ 20++ ),+ { status: 200, headers: { "Content-Type": "text/event-stream" } }+ );++ const result = await ensureStreamReadiness(response, { timeoutMs: 10 });+ assert.equal(result.ok, false);+ assert.equal(result.response.status, 504);+ assert.match(await result.response.text(), /STREAM_READINESS_TIMEOUT/);+ });++ test("ensureStreamReadiness returns 502 when stream ends without useful content", async () => {+ const response = new Response(streamFromChunks([": keepalive\n\n"]), {+ status: 200,+ headers: { "Content-Type": "text/event-stream" },+ });++ const result = await ensureStreamReadiness(response, { timeoutMs: 100 });+ assert.equal(result.ok, false);+ assert.equal(result.response.status, 502);+ });diff --cc tests/unit/usage-service-hardening.test.tsindex 6fab9408e5,bf17bb6546..7253465568--- a/tests/unit/usage-service-hardening.test.ts+++ b/tests/unit/usage-service-hardening.test.ts@@@ -407,6 -413,74 +413,76 @@@ test("usage service retries Antigravitassert.equal(usage.quotas["claude-sonnet-4-6"].used, 500);});+ test("usage service manual Antigravity refresh bypasses usage TTL caches", async () => {+ process.env.ANTIGRAVITY_CREDITS = "retry";+ let probeCalls = 0;+ let modelCalls = 0;++ globalThis.fetch = async (url) => {+ const urlStr = String(url);+ if (urlStr.includes("loadCodeAssist")) {- return new Response(JSON.stringify({ cloudaicompanionProject: "ag-project" }), { status: 200 });++ return new Response(JSON.stringify({ cloudaicompanionProject: "ag-project" }), {++ status: 200,++ });+ }++ if (urlStr.includes("streamGenerateContent")) {+ probeCalls++;+ return new Response(+ `data: ${JSON.stringify({ remainingCredits: [{ creditType: "GOOGLE_ONE_AI", creditAmount: String(100 - probeCalls) }] })}\n\n`,+ { status: 200, headers: { "Content-Type": "text/event-stream" } }+ );+ }++ if (urlStr.includes("fetchAvailableModels")) {+ modelCalls++;+ return new Response(+ JSON.stringify({+ models: {+ "claude-sonnet-4-6": {+ quotaInfo: { remainingFraction: 1 },+ },+ },+ }),+ { status: 200, headers: { "Content-Type": "application/json" } }+ );+ }++ throw new Error(`unexpected fetch: ${url}`);+ };++ const connection = {+ id: "ag-manual-refresh-service-test",+ provider: "antigravity",+ accessToken: "ag-manual-service-token",+ projectId: "ag-project",+ };++ await usageService.getUsageForProvider(connection, { forceRefresh: true });+ await usageService.getUsageForProvider(connection, { forceRefresh: true });++ assert.equal(probeCalls, 2);+ assert.equal(modelCalls, 2);+ });++ test("usage service handles missing Antigravity access tokens without probing upstream", async () => {+ let fetchCalls = 0;++ globalThis.fetch = async () => {+ fetchCalls++;+ return new Response("unexpected", { status: 500 });+ };++ const usage: any = await usageService.getUsageForProvider({+ provider: "antigravity",+ accessToken: undefined,+ });++ assert.equal(fetchCalls, 0);+ assert.equal(usage.plan, "Free");+ assert.match(usage.message, /Antigravity access token not available/i);+ });+test("usage service covers Antigravity tier fallbacks and non-403 upstream failures", async () => {globalThis.fetch = async (url) => {if (String(url).includes("loadCodeAssist")) {