Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,8 @@ icon.iconset/

# VS Code Extension (independent Git repo)
vscode-extension/

# SQLite residual files
*.sqlite-shm
*.sqlite-wal
*.sqlite-journal
35 changes: 19 additions & 16 deletions open-sse/services/usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/

import { PROVIDERS } from "../config/constants.ts";
import { safePercentage } from "@/shared/utils/formatting";

// GitHub API config
const GITHUB_CONFIG = {
Expand Down Expand Up @@ -34,6 +35,7 @@ const CLAUDE_CONFIG = {
oauthUsageUrl: "https://api.anthropic.com/api/oauth/usage",
usageUrl: "https://api.anthropic.com/v1/organizations/{org_id}/usage",
settingsUrl: "https://api.anthropic.com/v1/settings",
apiVersion: "2023-06-01",
};

type JsonRecord = Record<string, unknown>;
Expand Down Expand Up @@ -469,44 +471,42 @@ async function getClaudeUsage(accessToken) {
headers: {
Authorization: `Bearer ${accessToken}`,
"anthropic-beta": "oauth-2025-04-20",
"anthropic-version": "2023-06-01",
"anthropic-version": CLAUDE_CONFIG.apiVersion,
},
});

if (oauthResponse.ok) {
const data = await oauthResponse.json();
const quotas: Record<string, any> = {};

// utilization = percentage USED (e.g., 22 means 22% used, 78% remaining)
// utilization = percentage REMAINING (e.g., 90 means 90% remaining, 10% used)
const hasUtilization = (window: any) =>
window && typeof window === "object" && safePercentage(window.utilization) !== undefined;

const createQuotaObject = (window: any) => {
const used = window?.utilization ?? 0;
const remaining = 100 - used;
const remaining = safePercentage(window.utilization) as number;
const used = 100 - remaining;
return {
used,
total: 100,
remaining,
resetAt: parseResetTime(window?.resets_at),
resetAt: parseResetTime(window.resets_at),
Comment thread
DavyMassoneto marked this conversation as resolved.
Resolved
remainingPercentage: remaining,
unlimited: false,
};
};

if (data.five_hour && typeof data.five_hour === "object") {
if (hasUtilization(data.five_hour)) {
quotas["session (5h)"] = createQuotaObject(data.five_hour);
}

if (data.seven_day && typeof data.seven_day === "object") {
if (hasUtilization(data.seven_day)) {
quotas["weekly (7d)"] = createQuotaObject(data.seven_day);
}

// Parse model-specific weekly windows (e.g., seven_day_sonnet, seven_day_opus)
for (const [key, value] of Object.entries(data)) {
if (
key.startsWith("seven_day_") &&
key !== "seven_day" &&
value &&
typeof value === "object"
) {
if (key.startsWith("seven_day_") && key !== "seven_day" && hasUtilization(value)) {
const modelName = key.replace("seven_day_", "");
quotas[`weekly ${modelName} (7d)`] = createQuotaObject(value);
}
Expand All @@ -519,7 +519,10 @@ async function getClaudeUsage(accessToken) {
};
}

// Fallback: Try legacy settings/org endpoint (for API key users with org admin access)
// Fallback: OAuth endpoint returned non-OK, try legacy settings/org endpoint
console.warn(
`[Claude Usage] OAuth endpoint returned ${oauthResponse.status}, falling back to legacy`
);
return await getClaudeUsageLegacy(accessToken);
} catch (error) {
return { message: `Claude connected. Unable to fetch usage: ${(error as any).message}` };
Expand All @@ -536,7 +539,7 @@ async function getClaudeUsageLegacy(accessToken) {
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"anthropic-version": "2023-06-01",
"anthropic-version": CLAUDE_CONFIG.apiVersion,
},
});

Expand All @@ -550,7 +553,7 @@ async function getClaudeUsageLegacy(accessToken) {
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"anthropic-version": "2023-06-01",
"anthropic-version": CLAUDE_CONFIG.apiVersion,
},
}
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,9 @@ export default function ProviderLimitCard({
{!loading && !error && !message && quotas?.length > 0 && (
<div className="space-y-4">
{quotas.map((quota, index) => {
// For Antigravity, use remainingPercentage if available, otherwise calculate
const percentage =
quota.remainingPercentage !== undefined
? Math.round(((quota.total - quota.used) / quota.total) * 100)
? Math.round(quota.remainingPercentage)
: calculatePercentage(quota.used, quota.total);
const unlimited = quota.total === 0 || quota.total === null;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getModelsByProviderId } from "@omniroute/open-sse/config/providerModels.ts";
import { safePercentage } from "@/shared/utils/formatting";

/**
* Format ISO date string to countdown format (inspired by vscode-antigravity-cockpit)
Expand Down Expand Up @@ -110,7 +111,7 @@ export function parseQuotaData(provider, data) {
used: quota.used || 0,
total: quota.total || 0,
resetAt: quota.resetAt || null,
remainingPercentage: quota.remainingPercentage,
remainingPercentage: safePercentage(quota.remainingPercentage),
});
});
}
Expand Down Expand Up @@ -159,7 +160,7 @@ export function parseQuotaData(provider, data) {
used: quota.used || 0,
total: quota.total || 0,
resetAt: quota.resetAt || null,
remainingPercentage: quota.remainingPercentage,
remainingPercentage: safePercentage(quota.remainingPercentage),
});
});
}
Expand Down
11 changes: 11 additions & 0 deletions src/app/api/usage/[connectionId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { getUsageForProvider } from "@omniroute/open-sse/services/usage.ts";
import { getExecutor } from "@omniroute/open-sse/executors/index.ts";
import { syncToCloud } from "@/lib/cloudSync";
import { runWithProxyContext } from "@omniroute/open-sse/utils/proxyFetch.ts";
import { setQuotaCache } from "@/domain/quotaCache";

function isRecord(value: unknown): value is Record<string, any> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}

/**
* Sync to cloud if enabled
Expand Down Expand Up @@ -147,6 +152,12 @@ export async function GET(request: Request, { params }: { params: Promise<{ conn
const usage = await runWithProxyContext(proxyInfo?.proxy || null, () =>
getUsageForProvider(connection)
);

// Populate quota cache for quota-aware account selection
if (isRecord(usage?.quotas)) {
setQuotaCache(connectionId, connection.provider, usage.quotas);
}

return Response.json(usage);
} catch (error) {
console.error("[Usage API] Error fetching usage:", error);
Expand Down
3 changes: 3 additions & 0 deletions src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
directives ensure all utility classes in route groups are included. */
@source "../app/(dashboard)";
@source "../../open-sse";
@source not "../../*.sqlite*";
@source not "../../.claude*";
@source not "../../.claude-memory";

@custom-variant dark (&:where(.dark, .dark *));

Expand Down
Loading