-
-
Notifications
You must be signed in to change notification settings - Fork 572
Expand file tree
/
Copy pathrefresh-usage.ts
More file actions
69 lines (58 loc) · 1.81 KB
/
refresh-usage.ts
File metadata and controls
69 lines (58 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import consola from "consola"
import { state } from "./state"
import { getCopilotUsage } from "~/services/github/get-copilot-usage"
// Cache configuration
const USAGE_CACHE_TTL_MS = 60 * 1000 // 1 minute cache
let lastUsageFetchTime = 0
let isFetching = false
/**
* Refresh premium interactions usage information
* with cache to avoid excessive API calls
*/
export async function refreshUsage(): Promise<void> {
const now = Date.now()
// Check if cache is still valid
if (now - lastUsageFetchTime < USAGE_CACHE_TTL_MS) {
consola.debug(
`Using cached usage info (cached ${Math.floor((now - lastUsageFetchTime) / 1000)}s ago)`,
)
return
}
// Prevent concurrent fetches
if (isFetching) {
consola.debug("Usage fetch already in progress, skipping")
return
}
try {
isFetching = true
consola.debug("Fetching latest usage information...")
const usage = await getCopilotUsage()
state.premiumInteractions = usage.quota_snapshots.premium_interactions
lastUsageFetchTime = now
const usagePercent = 100 - state.premiumInteractions.percent_remaining
consola.debug(
`✓ Usage refreshed: ${usagePercent.toFixed(1)}% (${state.premiumInteractions.remaining}/${state.premiumInteractions.entitlement} remaining)`,
)
} catch (error) {
consola.warn("Failed to refresh usage information:", error)
// Continue with existing state - don't block the main flow
} finally {
isFetching = false
}
}
/**
* Force refresh usage (bypass cache)
*/
export async function forceRefreshUsage(): Promise<void> {
lastUsageFetchTime = 0
await refreshUsage()
}
/**
* Get current usage percentage
*/
export function getCurrentUsagePercent(): number | null {
if (!state.premiumInteractions) {
return null
}
return 100 - state.premiumInteractions.percent_remaining
}