YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(usage): show Cloudflare AI usage percentages in app settings (#5941)
Ezra Ellette448e42e8bc03
diff --git a/apps/screenpipe-app-tauri/components/settings/usage-section.tsx b/apps/screenpipe-app-tauri/components/settings/usage-section.tsxindex 310d7de0f..9425bcf58 100644--- a/apps/screenpipe-app-tauri/components/settings/usage-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/usage-section.tsx@@ -8,7 +8,7 @@ import type { SettingsField } from "./settings-search";/** Settings search index for this section. Co-located with the component so adding a field here means updating one file. See `SettingsField` in `./settings-search` for the schema. */export const searchIndex: SettingsField[] = [- { label: "Usage stats", keywords: ["stats", "activity", "analytics", "metrics"] },+ { label: "Usage stats", keywords: ["stats", "activity", "analytics", "metrics", "ai", "allowance", "quota", "percent"] },];import { Card, CardContent } from "@/components/ui/card";import { Skeleton } from "@/components/ui/skeleton";@@ -17,6 +17,13 @@ import { loadAllConversations } from "@/lib/chat-storage";import { homeDir, join } from "@tauri-apps/api/path";import { readTextFile, writeTextFile, exists } from "@tauri-apps/plugin-fs";import { localFetch } from "@/lib/api";+import {+ useUsageStatus,+ formatUsagePercent,+ formatAllowanceWindow,+ formatAllowanceReset,+ type HostedAiAllowance,+} from "@/lib/hooks/use-usage-status";type TimeRange = "day" | "week" | "month" | "all";@@ -137,7 +144,63 @@ function getTimeSince(range: TimeRange): number | undefined {}}+function AllowanceMeter({ allowance }: { allowance: HostedAiAllowance }) {+ const laneLabel =+ allowance.lane === "combined"+ ? "all models"+ : allowance.lane === "auto"+ ? "auto"+ : "manual";+ const windowLabel = formatAllowanceWindow(allowance.window_seconds);+ const resetLabel = allowance.resets_at+ ? formatAllowanceReset(allowance.resets_at)+ : null;+ const isLow = allowance.remaining_percent < 30;+ const isExhausted = allowance.remaining_percent <= 0;++ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between text-sm">+ <span className="font-medium capitalize">+ {allowance.lane === "combined" ? laneLabel : `${laneLabel} model`}+ </span>+ <span+ className={`font-mono text-xs ${+ isExhausted+ ? "text-red-500"+ : isLow+ ? "text-yellow-500"+ : "text-muted-foreground"+ }`}+ >+ {formatUsagePercent(allowance.used_percent)} used+ </span>+ </div>+ <div className="h-2 bg-muted rounded-full overflow-hidden">+ <div+ className={`h-full rounded-full transition-all ${+ isExhausted+ ? "bg-red-500"+ : isLow+ ? "bg-yellow-500"+ : "bg-foreground/30"+ }`}+ style={{ width: `${Math.min(100, allowance.used_percent)}%` }}+ />+ </div>+ <div className="flex items-center justify-between text-xs text-muted-foreground">+ <span>+ {formatUsagePercent(allowance.remaining_percent)} remaining+ {` · ${windowLabel} ${allowance.technique} window`}+ </span>+ {resetLabel && <span>resets {resetLabel}</span>}+ </div>+ </div>+ );+}+export function UsageSection() {+ const hostedUsage = useUsageStatus();const [entries, setEntries] = useState<UsageEntry[]>([]);const [totalChats, setTotalChats] = useState(0);const [totalChatMessages, setTotalChatMessages] = useState(0);@@ -387,6 +450,38 @@ export function UsageSection() {<p className="text-xs text-muted-foreground">Updating...</p>)}+ {/* Cloudflare AI usage allowances */}+ {hostedUsage?.hosted_ai?.allowances && hostedUsage.hosted_ai.allowances.length > 0 && (+ <Card>+ <CardContent className="pt-6 space-y-4">+ <div className="flex items-center justify-between">+ <h3 className="text-sm font-medium">AI usage</h3>+ {hostedUsage.hosted_ai.plan && (+ <span className="text-xs text-muted-foreground capitalize">+ {hostedUsage.hosted_ai.plan} plan+ </span>+ )}+ </div>+ {hostedUsage.hosted_ai.allowances.map((allowance, index) => (+ <AllowanceMeter key={`${allowance.lane}-${index}`} allowance={allowance} />+ ))}+ {hostedUsage.hosted_ai.upgrade && (+ <p className="text-xs text-muted-foreground">+ need more?{" "}+ <a+ href={hostedUsage.hosted_ai.upgrade.upgradeUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="underline hover:text-foreground"+ >+ upgrade to {hostedUsage.hosted_ai.upgrade.requiredPlan}+ </a>+ </p>+ )}+ </CardContent>+ </Card>+ )}+<div className="grid grid-cols-3 gap-4"><Card><CardContent className="pt-6">diff --git a/apps/screenpipe-app-tauri/lib/dev/browser-tauri-mock.ts b/apps/screenpipe-app-tauri/lib/dev/browser-tauri-mock.tsindex 370a72f7f..3d23ba3c7 100644--- a/apps/screenpipe-app-tauri/lib/dev/browser-tauri-mock.ts+++ b/apps/screenpipe-app-tauri/lib/dev/browser-tauri-mock.ts@@ -428,6 +428,8 @@ export function createBrowserIpcMock(options: BrowserIpcMockOptions) {managed: false,detected_by: [],};+ case "get_screenpipe_ai_gateway_url":+ return "https://api.screenpipe.com/v1";case "is_enterprise_build_cmd":case "is_capture_paused":return false;diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-usage-status.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-usage-status.tsxindex 4a049d95b..90b3d5671 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-usage-status.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-usage-status.tsx@@ -28,7 +28,7 @@ export type UsageTier =| "business_max"| "business_ultra";-export type HostedAiLane = "auto" | "explicit";+export type HostedAiLane = "auto" | "explicit" | "combined";export interface HostedAiAllowance {lane: HostedAiLane;@@ -74,7 +74,7 @@ function parseHostedAiAllowance(value: unknown): HostedAiAllowance | null {if (!value || typeof value !== "object") return null;const candidate = value as Partial<HostedAiAllowance>;if (- (candidate.lane !== "auto" && candidate.lane !== "explicit") ||+ (candidate.lane !== "auto" && candidate.lane !== "explicit" && candidate.lane !== "combined") ||(candidate.technique !== "fixed" && candidate.technique !== "sliding") ||(candidate.resets_at !== null && typeof candidate.resets_at !== "string")) {@@ -206,7 +206,8 @@ export function useUsageStatus(): UsageStatus | null {: null;}-/** Return the tightest Cloudflare allowance that applies to a model lane. */+/** Return the tightest Cloudflare allowance that applies to a model lane.+ * A 'combined' allowance covers all lanes and matches any lane query. */export function hostedAiAllowanceForLane(usage: UsageStatus | null,lane: HostedAiLane,@@ -214,7 +215,7 @@ export function hostedAiAllowanceForLane(const allowances = usage?.hosted_ai?.allowances;if (!allowances) return null;return allowances- .filter((allowance) => allowance.lane === lane)+ .filter((allowance) => allowance.lane === lane || allowance.lane === "combined").sort((left, right) => left.remaining_percent - right.remaining_percent)[0] ?? null;}diff --git a/packages/ai-gateway/src/services/cloudflare-ai-gateway-usage.ts b/packages/ai-gateway/src/services/cloudflare-ai-gateway-usage.tsindex 326ba095f..3a6064d53 100644--- a/packages/ai-gateway/src/services/cloudflare-ai-gateway-usage.ts+++ b/packages/ai-gateway/src/services/cloudflare-ai-gateway-usage.ts@@ -9,6 +9,10 @@ import type {HostedChatLane,} from './cloudflare-ai-gateway';+/** Allowance lane exposed to clients. 'combined' means the rule covers all+ * traffic for the user without distinguishing auto vs explicit. */+export type AllowanceLane = HostedChatLane | 'combined';+type SpendDimension = {mode: 'partition' | 'filter';values?: string[];@@ -25,11 +29,11 @@ type CloudflareSpendRule = {};type ApplicableSpendRule = CloudflareSpendRule & {- lane: HostedChatLane;+ lane: AllowanceLane;};export interface HostedChatUsageAllowance {- lane: HostedChatLane;+ lane: AllowanceLane;used_percent: number;remaining_percent: number;window_seconds: number;@@ -150,9 +154,14 @@ function filterMatches(dimension: SpendDimension | undefined, value: string): bo}/**- * Select the per-user lane rules represented by the desktop usage UI.+ * Select the per-user rules represented by the desktop usage UI.* Provider/model rules and rules partitioned by another dimension are separate- * buckets and cannot truthfully be collapsed into a single Auto/explicit meter.+ * buckets and cannot truthfully be collapsed into a single meter.+ *+ * Rules that filter to a single lane produce an 'auto' or 'explicit' allowance.+ * Rules with no lane dimension at all produce a 'combined' allowance that sums+ * all traffic for the user — this is the current production setup where auto+ * and explicit share a single spend limit.*/function applicableLaneRules(rules: CloudflareSpendRule[],@@ -165,9 +174,17 @@ function applicableLaneRules(dimension.mode === 'partition' && key !== 'user_id')) return [];if (!filterMatches(rule.metadata.plan, context.plan)) return [];const laneDimension = rule.metadata.lane;- if (laneDimension?.mode !== 'filter' || laneDimension.values?.length !== 1) return [];- const lane = laneDimension.values[0];- if (lane !== 'auto' && lane !== 'explicit') return [];+ let lane: AllowanceLane;+ if (!laneDimension) {+ // No lane dimension — rule covers all traffic for this user+plan.+ lane = 'combined';+ } else if (laneDimension.mode === 'filter' && laneDimension.values?.length === 1) {+ const value = laneDimension.values[0];+ if (value !== 'auto' && value !== 'explicit') return [];+ lane = value;+ } else {+ return [];+ }const unsupportedMetadata = Object.keys(rule.metadata).some((key) => !['user_id', 'plan', 'lane'].includes(key));return unsupportedMetadata ? [] : [{ ...rule, lane }];@@ -213,7 +230,7 @@ function ruleMatchesRow(): boolean {return row.user_id === context.user_id &&row.plan === context.plan &&- row.lane === rule.lane;+ (rule.lane === 'combined' || row.lane === rule.lane);}async function fetchUsageRows(diff --git a/packages/ai-gateway/src/test/cloudflare-ai-gateway-usage.unit.test.ts b/packages/ai-gateway/src/test/cloudflare-ai-gateway-usage.unit.test.tsindex e138a2b7f..11a6bd580 100644--- a/packages/ai-gateway/src/test/cloudflare-ai-gateway-usage.unit.test.ts+++ b/packages/ai-gateway/src/test/cloudflare-ai-gateway-usage.unit.test.ts@@ -225,6 +225,57 @@ describe('Cloudflare hosted-chat usage', () => {]);});+ it('handles a combined rule with no lane dimension', async () => {+ globalThis.fetch = mock(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes('/ai-gateway/gateways/combined-rule-test')) {+ return gatewayResponse([{+ id: 'basic-combined',+ enabled: true,+ limit: 10,+ limitType: 'cost',+ window: 86_400,+ technique: 'fixed',+ metadata: {+ user_id: { mode: 'partition' },+ plan: { mode: 'filter', values: ['basic'] },+ },+ }]);+ }+ if (url.endsWith('/graphql')) {+ return new Response(JSON.stringify({+ data: {+ viewer: {+ accounts: [{+ window0: [+ usageRow('auto', 'interactive', 3),+ usageRow('explicit', 'interactive', 2),+ ],+ }],+ },+ },+ }), { status: 200 });+ }+ throw new Error(`unexpected fetch: ${url}`);+ }) as typeof fetch;++ const result = await getCloudflareHostedChatUsage(+ env('combined-rule-test'),+ context,+ new Date('2026-08-04T16:30:00.000Z'),+ );++ expect(result?.allowances).toEqual([+ expect.objectContaining({+ lane: 'combined',+ used_percent: 50,+ remaining_percent: 50,+ window_seconds: 86_400,+ technique: 'fixed',+ }),+ ]);+ });+it('returns unavailable instead of a fabricated balance without read credentials', async () => {globalThis.fetch = mock(async () => {throw new Error('fetch should not run');