-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathusage-banner.tsx
More file actions
301 lines (273 loc) · 11.4 KB
/
usage-banner.tsx
File metadata and controls
301 lines (273 loc) · 11.4 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import { CHATGPT_OAUTH_ENABLED } from '@codebuff/common/constants/chatgpt-oauth'
import { CLAUDE_OAUTH_ENABLED } from '@codebuff/common/constants/claude-oauth'
import { IS_FREEBUFF } from '../utils/constants'
import { isChatGptOAuthValid, isClaudeOAuthValid } from '@codebuff/sdk'
import { TextAttributes } from '@opentui/core'
import { safeOpen } from '../utils/open-url'
import React, { useEffect, useMemo } from 'react'
import { BottomBanner } from './bottom-banner'
import { Button } from './button'
import { ProgressBar } from './progress-bar'
import { getActivityQueryData } from '../hooks/use-activity-query'
import { useClaudeQuotaQuery } from '../hooks/use-claude-quota-query'
import { useSubscriptionQuery } from '../hooks/use-subscription-query'
import { useTheme } from '../hooks/use-theme'
import { useUpdatePreference } from '../hooks/use-update-preference'
import { usageQueryKeys, useUsageQuery } from '../hooks/use-usage-query'
import { WEBSITE_URL } from '../login/constants'
import { useChatStore } from '../state/chat-store'
import { formatResetTime, formatResetTimeLong } from '../utils/time-format'
import {
getBannerColorLevel,
generateLoadingBannerText,
} from '../utils/usage-banner-state'
const MANUAL_SHOW_TIMEOUT = 60 * 1000 // 1 minute
const USAGE_POLL_INTERVAL = 30 * 1000 // 30 seconds
/**
* Format the renewal date for display
*/
const formatRenewalDate = (dateStr: string | null): string => {
if (!dateStr) return ''
const resetDate = new Date(dateStr)
const today = new Date()
const isToday = resetDate.toDateString() === today.toDateString()
return isToday
? resetDate.toLocaleString('en-US', {
hour: 'numeric',
minute: '2-digit',
})
: resetDate.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
})
}
export const UsageBanner = ({ showTime }: { showTime: number }) => {
if (IS_FREEBUFF) return null
const sessionCreditsUsed = useChatStore((state) => state.sessionCreditsUsed)
const setInputMode = useChatStore((state) => state.setInputMode)
// Check if Claude OAuth is connected (only when feature is enabled)
const isClaudeConnected = CLAUDE_OAUTH_ENABLED && isClaudeOAuthValid()
const isChatGptConnected = CHATGPT_OAUTH_ENABLED && isChatGptOAuthValid()
// Fetch Claude quota data if connected
const { data: claudeQuota, isLoading: isClaudeLoading } = useClaudeQuotaQuery({
enabled: isClaudeConnected,
refetchInterval: 30 * 1000, // Refresh every 30 seconds when banner is open
})
// Fetch subscription data
const { data: subscriptionData, isLoading: isSubscriptionLoading } = useSubscriptionQuery({
refetchInterval: 30 * 1000,
})
const {
data: apiData,
isLoading,
isFetching,
} = useUsageQuery({
enabled: true,
refetchInterval: USAGE_POLL_INTERVAL,
})
// Get cached data for immediate display
const cachedUsageData = getActivityQueryData<{
type: 'usage-response'
usage: number
remainingBalance: number | null
balanceBreakdown?: { free: number; paid: number; ad?: number }
next_quota_reset: string | null
}>(usageQueryKeys.current())
// Auto-hide after timeout
useEffect(() => {
const timer = setTimeout(() => {
setInputMode('default')
}, MANUAL_SHOW_TIMEOUT)
return () => clearTimeout(timer)
}, [showTime, setInputMode])
const theme = useTheme()
const activeData = apiData || cachedUsageData
const isLoadingData = isLoading || isFetching
// Show loading state immediately when banner is opened but data isn't ready
if (!activeData) {
return (
<BottomBanner
borderColorKey="muted"
text={generateLoadingBannerText(sessionCreditsUsed)}
onClose={() => setInputMode('default')}
/>
)
}
const colorLevel = getBannerColorLevel(activeData.remainingBalance)
const renewalDate = activeData.next_quota_reset ? formatRenewalDate(activeData.next_quota_reset) : null
const activeSubscription = subscriptionData?.hasSubscription ? subscriptionData : null
const { rateLimit, subscription: subscriptionInfo, displayName } = activeSubscription ?? {}
return (
<BottomBanner
borderColorKey={isLoadingData ? 'muted' : colorLevel}
onClose={() => setInputMode('default')}
>
<box style={{ flexDirection: 'column', gap: 0 }}>
{activeSubscription && (
<SubscriptionUsageSection
displayName={displayName}
subscriptionInfo={subscriptionInfo}
rateLimit={rateLimit}
isLoading={isSubscriptionLoading}
fallbackToALaCarte={activeSubscription.fallbackToALaCarte ?? false}
/>
)}
{/* Codebuff credits section - structured layout */}
<Button
onClick={() => {
safeOpen(WEBSITE_URL + '/usage')
}}
>
<box style={{ flexDirection: 'column', gap: 0 }}>
{/* Main stats row */}
<box style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 1 }}>
<text style={{ fg: theme.muted }}>Session:</text>
<text style={{ fg: theme.foreground }}>{sessionCreditsUsed.toLocaleString()} credits</text>
<text style={{ fg: theme.muted }}>·</text>
<text style={{ fg: theme.muted }}>Remaining:</text>
{isLoadingData ? (
<text style={{ fg: theme.muted }}>...</text>
) : (
<text style={{ fg: theme.foreground }}>
{activeData.remainingBalance?.toLocaleString() ?? '?'} credits
</text>
)}
{!activeSubscription && renewalDate && (
<>
<text style={{ fg: theme.muted }}>· Renews:</text>
<text style={{ fg: theme.foreground }}>{renewalDate}</text>
</>
)}
</box>
{/* See more link */}
<text style={{ fg: theme.muted }}>See more on {WEBSITE_URL} ↗</text>
</box>
</Button>
{/* Claude subscription section - only show if connected */}
{isClaudeConnected && (
<box style={{ flexDirection: 'column', marginTop: 1 }}>
<text style={{ fg: theme.muted }}>Claude subscription</text>
{isClaudeLoading ? (
<text style={{ fg: theme.muted }}>Loading quota...</text>
) : claudeQuota ? (
<box style={{ flexDirection: 'column', gap: 0 }}>
<box style={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
<text style={{ fg: theme.muted }}>5-hour:</text>
<ProgressBar value={claudeQuota.fiveHourRemaining} width={15} />
{claudeQuota.fiveHourResetsAt && (
<text style={{ fg: theme.muted }}>
(resets in {formatResetTime(claudeQuota.fiveHourResetsAt)})
</text>
)}
</box>
{/* Only show 7-day bar if the user has a 7-day limit */}
{claudeQuota.sevenDayResetsAt && (
<box style={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
<text style={{ fg: theme.muted }}>7-day: </text>
<ProgressBar value={claudeQuota.sevenDayRemaining} width={15} />
<text style={{ fg: theme.muted }}>
(resets in {formatResetTime(claudeQuota.sevenDayResetsAt)})
</text>
</box>
)}
</box>
) : (
<text style={{ fg: theme.muted }}>Unable to fetch quota</text>
)}
</box>
)}
{isChatGptConnected && (
<box style={{ flexDirection: 'column', marginTop: 1 }}>
<text style={{ fg: theme.muted }}>ChatGPT subscription</text>
<text style={{ fg: theme.muted }}>
Connected for supported OpenAI streaming models
</text>
</box>
)}
</box>
</BottomBanner>
)
}
interface SubscriptionUsageSectionProps {
displayName?: string
subscriptionInfo?: { tier: number }
rateLimit?: {
blockLimit?: number
blockUsed?: number
blockResetsAt?: string
weeklyPercentUsed: number
weeklyResetsAt: string
}
isLoading: boolean
fallbackToALaCarte: boolean
}
const SubscriptionUsageSection: React.FC<SubscriptionUsageSectionProps> = ({
displayName,
subscriptionInfo,
rateLimit,
isLoading,
fallbackToALaCarte,
}) => {
const theme = useTheme()
const updatePreference = useUpdatePreference()
const handleToggleFallbackToALaCarte = () => {
updatePreference.mutate({ fallbackToALaCarte: !fallbackToALaCarte })
}
const blockPercent = useMemo(() => {
if (rateLimit?.blockLimit == null || rateLimit.blockUsed == null) return 100
return Math.max(0, 100 - Math.round((rateLimit.blockUsed / rateLimit.blockLimit) * 100))
}, [rateLimit?.blockLimit, rateLimit?.blockUsed])
const weeklyPercent = rateLimit ? 100 - rateLimit.weeklyPercentUsed : 100
return (
<box style={{ flexDirection: 'column', marginBottom: 1 }}>
<box style={{ flexDirection: 'row', gap: 1 }}>
<text style={{ fg: theme.foreground }}>
💪 {displayName ?? 'Strong'} subscription
</text>
{subscriptionInfo?.tier && (
<text style={{ fg: theme.muted }}>${subscriptionInfo.tier}/mo</text>
)}
</box>
{isLoading ? (
<text style={{ fg: theme.muted }}>Loading subscription data...</text>
) : rateLimit ? (
<box style={{ flexDirection: 'column', gap: 0 }}>
<box style={{ flexDirection: 'row', alignItems: 'center', gap: 0 }}>
<text style={{ fg: theme.muted }}>{`5-hour limit ${`${blockPercent}%`.padStart(4)} `}</text>
<ProgressBar value={blockPercent} width={12} showPercentage={false} />
<text style={{ fg: theme.muted }}>
{rateLimit.blockResetsAt
? ` resets in ${formatResetTime(new Date(rateLimit.blockResetsAt))}`
: ''}
</text>
</box>
<box style={{ flexDirection: 'row', alignItems: 'center', gap: 0 }}>
<text style={{ fg: theme.muted }}>{`Weekly limit ${`${weeklyPercent}%`.padStart(4)} `}</text>
<ProgressBar value={weeklyPercent} width={12} showPercentage={false} />
<text style={{ fg: theme.muted }}>
{` resets in ${formatResetTimeLong(rateLimit.weeklyResetsAt)}`}
</text>
</box>
</box>
) : null}
<box style={{ flexDirection: 'column', gap: 0, marginTop: 1 }}>
<box style={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
<text style={{ fg: theme.muted }}>Credit spending:</text>
<text style={{ fg: fallbackToALaCarte ? theme.foreground : theme.warning }}>
{fallbackToALaCarte ? 'enabled' : 'disabled'}
</text>
<Button onClick={handleToggleFallbackToALaCarte} disabled={updatePreference.isPending}>
<text style={{ fg: theme.muted, attributes: TextAttributes.UNDERLINE }}>
{updatePreference.isPending ? '[updating...]' : `[${fallbackToALaCarte ? 'disable' : 'enable'}]`}
</text>
</Button>
</box>
<text style={{ fg: theme.muted }}>
{fallbackToALaCarte
? 'Your credits will be used when subscription limits are reached.'
: 'Credits will NOT be spent when subscription limits are reached. Enable to use credits.'}
</text>
</box>
</box>
)
}