forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodex-usage-dialog.tsx
More file actions
1354 lines (1261 loc) · 40.4 KB
/
Copy pathcodex-usage-dialog.tsx
File metadata and controls
1354 lines (1261 loc) · 40.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
Copy,
Check,
RefreshCw,
ChevronDown,
ChevronUp,
RotateCcw,
AlertTriangle,
} from 'lucide-react'
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type ReactNode, useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { Dialog } from '@/components/dialog'
import { StatusBadge, type StatusBadgeProps } from '@/components/status-badge'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible'
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyTitle,
} from '@/components/ui/empty'
import { Progress } from '@/components/ui/progress'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Skeleton } from '@/components/ui/skeleton'
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'
import dayjs from '@/lib/dayjs'
import { formatDateTimeStr, formatTimestampToDate } from '@/lib/format'
import { cn } from '@/lib/utils'
import {
getCodexResetCredits,
resetCodexUsage,
type CodexResetCreditsResponse,
} from '../../api'
type CodexRateLimitWindow = {
used_percent?: number
reset_at?: number
reset_after_seconds?: number
limit_window_seconds?: number
}
type CodexRateLimit = {
plan_type?: string
allowed?: boolean
limit_reached?: boolean
primary_window?: CodexRateLimitWindow
secondary_window?: CodexRateLimitWindow
}
type CodexAdditionalRateLimit = {
limit_name?: string
metered_feature?: string
rate_limit?: CodexRateLimit
primary_window?: CodexRateLimitWindow
secondary_window?: CodexRateLimitWindow
plan_type?: string
}
type CodexResetCredit = {
id?: string
reset_type?: string
status?: string
granted_at?: string | null
expires_at?: string | null
redeem_started_at?: string | null
redeemed_at?: string | null
profile_image_url?: string
profile_user_id?: string
title?: string
description?: string
}
type CodexResetCreditsPayload = {
credits?: CodexResetCredit[]
available_count?: number
total_earned_count?: number
}
type CodexUsagePayload = {
plan_type?: string
user_id?: string
email?: string
rate_limit?: CodexRateLimit
additional_rate_limits?: CodexAdditionalRateLimit[]
rate_limit_reset_credits?: {
available_count?: number
}
credits?: {
overage_limit_reached?: boolean
}
spend_control?: {
reached?: boolean
}
}
export type CodexUsageDialogData = {
success: boolean
message?: string
upstream_status?: number
data?: Record<string, unknown>
}
type CodexUsageDialogProps = {
open: boolean
onOpenChange: (open: boolean) => void
channelName?: string
channelId?: number
channelDisplayName?: string
channelDisplayId?: string
response: CodexUsageDialogData | null
onRefresh?: () => void | Promise<void>
isRefreshing?: boolean
}
function clampPercent(value: unknown): number {
const v = Number(value)
return Number.isFinite(v) ? Math.max(0, Math.min(100, v)) : 0
}
function formatUnixSeconds(unixSeconds: unknown): string {
const v = Number(unixSeconds)
return Number.isFinite(v) && v > 0 ? formatTimestampToDate(v) : '-'
}
function formatIsoTimestamp(value: unknown): string {
if (typeof value !== 'string' || value.trim() === '') {
return '-'
}
const d = dayjs(value)
if (!d.isValid()) {
return value
}
return formatDateTimeStr(d.toDate())
}
function formatDurationSeconds(
seconds: unknown,
t: (key: string) => string
): string {
const s = Number(seconds)
if (!Number.isFinite(s) || s <= 0) {
return '-'
}
const total = Math.floor(s)
const hours = Math.floor(total / 3600)
const minutes = Math.floor((total % 3600) / 60)
const secs = total % 60
if (hours > 0) {
return `${hours}${t('h')} ${minutes}${t('m')}`
}
if (minutes > 0) {
return `${minutes}${t('m')} ${secs}${t('s')}`
}
return `${secs}${t('s')}`
}
function formatTimeLeftUntil(
value: unknown,
t: (key: string) => string
): string {
if (typeof value !== 'string' || value.trim() === '') {
return '-'
}
const expiresAt = dayjs(value)
if (!expiresAt.isValid()) {
return '-'
}
const secondsLeft = expiresAt.diff(dayjs(), 'second')
if (secondsLeft <= 0) {
return t('Expired')
}
const days = Math.floor(secondsLeft / (24 * 60 * 60))
const remainingSeconds = secondsLeft % (24 * 60 * 60)
if (days > 0) {
const hours = Math.floor(remainingSeconds / 3600)
return `${days} ${t('days')} ${hours}${t('h')}`
}
return formatDurationSeconds(secondsLeft, t)
}
function normalizePlanType(value: unknown): string {
if (value == null) {
return ''
}
return String(value).trim().toLowerCase()
}
function parseTimeValue(value: unknown): number {
if (typeof value !== 'string' || value.trim() === '') {
return Number.POSITIVE_INFINITY
}
const d = dayjs(value)
return d.isValid() ? d.valueOf() : Number.POSITIVE_INFINITY
}
function normalizeResetCreditStatus(value: unknown): string {
return String(value || '')
.trim()
.toLowerCase()
}
function sortResetCredits(credits: CodexResetCredit[]): CodexResetCredit[] {
return [...credits].sort((a, b) => {
const aAvailable = normalizeResetCreditStatus(a.status) === 'available'
const bAvailable = normalizeResetCreditStatus(b.status) === 'available'
if (aAvailable !== bAvailable) {
return aAvailable ? -1 : 1
}
const expiresDiff =
parseTimeValue(a.expires_at) - parseTimeValue(b.expires_at)
if (expiresDiff !== 0) {
return expiresDiff
}
const grantedDiff =
parseTimeValue(a.granted_at) - parseTimeValue(b.granted_at)
if (grantedDiff !== 0) {
return grantedDiff
}
return String(a.id || '').localeCompare(String(b.id || ''))
})
}
function classifyWindowByDuration(
windowData?: CodexRateLimitWindow | null
): 'weekly' | 'fiveHour' | null {
const seconds = Number(windowData?.limit_window_seconds)
if (!Number.isFinite(seconds) || seconds <= 0) {
return null
}
return seconds >= 24 * 60 * 60 ? 'weekly' : 'fiveHour'
}
type RateLimitSource = {
plan_type?: string
rate_limit?: CodexRateLimit
}
function resolveRateLimitWindows(data: RateLimitSource | null): {
fiveHourWindow: CodexRateLimitWindow | null
weeklyWindow: CodexRateLimitWindow | null
} {
const rateLimit = data?.rate_limit ?? {}
const primary = rateLimit?.primary_window ?? null
const secondary = rateLimit?.secondary_window ?? null
const windows = [primary, secondary].filter(Boolean) as CodexRateLimitWindow[]
const planType = normalizePlanType(data?.plan_type ?? rateLimit?.plan_type)
let fiveHourWindow: CodexRateLimitWindow | null = null
let weeklyWindow: CodexRateLimitWindow | null = null
for (const w of windows) {
const bucket = classifyWindowByDuration(w)
if (bucket === 'fiveHour' && !fiveHourWindow) {
fiveHourWindow = w
continue
}
if (bucket === 'weekly' && !weeklyWindow) {
weeklyWindow = w
}
}
if (planType === 'free') {
if (!weeklyWindow) {
weeklyWindow = primary ?? secondary ?? null
}
return { fiveHourWindow: null, weeklyWindow }
}
if (!fiveHourWindow && !weeklyWindow) {
return { fiveHourWindow: primary, weeklyWindow: secondary }
}
if (!fiveHourWindow) {
fiveHourWindow = windows.find((w) => w !== weeklyWindow) ?? null
}
if (!weeklyWindow) {
weeklyWindow = windows.find((w) => w !== fiveHourWindow) ?? null
}
return { fiveHourWindow, weeklyWindow }
}
const PLAN_TYPE_BADGE: Record<
string,
{ label: string; variant: StatusBadgeProps['variant'] }
> = {
enterprise: { label: 'Enterprise', variant: 'success' },
team: { label: 'Team', variant: 'info' },
pro: { label: 'Pro', variant: 'blue' },
plus: { label: 'Plus', variant: 'purple' },
free: { label: 'Free', variant: 'warning' },
}
const RESET_CREDIT_STATUS_BADGE: Record<
string,
{ label: string; variant: StatusBadgeProps['variant'] }
> = {
available: { label: 'Available', variant: 'success' },
redeemed: { label: 'Redeemed', variant: 'neutral' },
expired: { label: 'Expired', variant: 'warning' },
}
function getAccountTypeBadge(
value: unknown,
t: (key: string) => string
): { label: string; variant: StatusBadgeProps['variant'] } {
const normalized = normalizePlanType(value)
return (
PLAN_TYPE_BADGE[normalized] ?? {
label: String(value || '') || t('Unknown'),
variant: 'neutral' as const,
}
)
}
function getResetCreditStatusBadge(
value: unknown,
t: (key: string) => string
): { label: string; variant: StatusBadgeProps['variant'] } {
const normalized = normalizeResetCreditStatus(value)
return (
RESET_CREDIT_STATUS_BADGE[normalized] ?? {
label: String(value || '') || t('Unknown'),
variant: 'neutral' as const,
}
)
}
function windowLabel(windowData?: CodexRateLimitWindow | null) {
const percent = clampPercent(windowData?.used_percent)
let variant: StatusBadgeProps['variant'] = 'info'
if (percent >= 95) {
variant = 'danger'
} else if (percent >= 80) {
variant = 'warning'
}
return { percent, variant }
}
function getUsageStatusBadge(
rateLimit: CodexRateLimit | undefined,
t: (key: string) => string
) {
if (!rateLimit || Object.keys(rateLimit).length === 0) {
return (
<StatusBadge label={t('Pending')} variant='neutral' copyable={false} />
)
}
if (rateLimit.allowed && !rateLimit.limit_reached) {
return (
<StatusBadge label={t('Available')} variant='success' copyable={false} />
)
}
return <StatusBadge label={t('Limited')} variant='danger' copyable={false} />
}
function formatLabelValue(label: string, value: string) {
return label.endsWith(':') ? `${label}${value}` : `${label} ${value}`
}
const percentTextClassName: Record<
NonNullable<StatusBadgeProps['variant']>,
string
> = {
success: 'text-success',
warning: 'text-warning',
danger: 'text-destructive',
info: 'text-info',
neutral: 'text-muted-foreground',
purple: 'text-chart-4',
amber: 'text-warning',
blue: 'text-chart-1',
cyan: 'text-chart-2',
green: 'text-success',
grey: 'text-muted-foreground',
indigo: 'text-chart-1',
'light-blue': 'text-info',
'light-green': 'text-emerald-500 dark:text-emerald-300',
lime: 'text-chart-3',
orange: 'text-warning',
pink: 'text-chart-5',
red: 'text-destructive',
teal: 'text-chart-2',
violet: 'text-chart-4',
yellow: 'text-warning',
}
type RateLimitWindowProps = {
title: string
window?: CodexRateLimitWindow | null
}
function RateLimitWindow(props: RateLimitWindowProps) {
const { t } = useTranslation()
const hasData =
!!props.window &&
typeof props.window === 'object' &&
Object.keys(props.window).length > 0
const { percent, variant } = windowLabel(props.window)
return (
<Card size='sm' className='gap-0 py-0'>
<CardHeader className='p-3 pb-2'>
<div className='flex items-start justify-between gap-3'>
<div className='min-w-0'>
<CardTitle className='text-sm font-semibold'>
{props.title}
</CardTitle>
<CardDescription className='mt-1 text-xs'>
{t('Window:')}{' '}
{hasData
? formatDurationSeconds(props.window?.limit_window_seconds, t)
: '-'}
</CardDescription>
</div>
<div className='shrink-0 text-right'>
<div
className={cn(
'text-xl leading-none font-semibold tabular-nums',
percentTextClassName[variant ?? 'neutral']
)}
>
{hasData ? `${percent}%` : '-'}
</div>
<div className='text-muted-foreground mt-1 text-[11px]'>
{t('Used')}
</div>
</div>
</div>
</CardHeader>
<CardContent className='p-3 pt-0'>
{hasData ? (
<Progress
value={percent}
aria-label={`${props.title} usage: ${percent}%`}
className='mt-1'
/>
) : (
<div className='text-muted-foreground mt-1 text-sm'>-</div>
)}
<div className='mt-3 grid grid-cols-1 gap-2 text-xs sm:grid-cols-2'>
<div className='min-w-0'>
<div className='text-muted-foreground text-[11px]'>
{t('Reset at:')}
</div>
<div className='break-all tabular-nums'>
{hasData ? formatUnixSeconds(props.window?.reset_at) : '-'}
</div>
</div>
<div className='min-w-0 sm:text-right'>
<div className='text-muted-foreground text-[11px]'>
{t('Resets in:')}
</div>
<div className='tabular-nums'>
{hasData
? formatDurationSeconds(props.window?.reset_after_seconds, t)
: '-'}
</div>
</div>
</div>
</CardContent>
</Card>
)
}
function RateLimitWindowGrid(props: {
fiveHourWindow?: CodexRateLimitWindow | null
weeklyWindow?: CodexRateLimitWindow | null
}) {
const { t } = useTranslation()
return (
<div className='grid grid-cols-1 gap-3 md:grid-cols-2'>
<RateLimitWindow
title={t('5-Hour Window')}
window={props.fiveHourWindow}
/>
<RateLimitWindow title={t('Weekly Window')} window={props.weeklyWindow} />
</div>
)
}
function SectionHeading(props: {
title: string
description?: string
children?: ReactNode
}) {
return (
<div className='flex flex-wrap items-start justify-between gap-3'>
<div className='min-w-0'>
<div className='text-sm font-semibold'>{props.title}</div>
{props.description ? (
<div className='text-muted-foreground mt-1 text-xs leading-5'>
{props.description}
</div>
) : null}
</div>
{props.children ? (
<div className='flex shrink-0 flex-wrap items-center gap-2'>
{props.children}
</div>
) : null}
</div>
)
}
type RateLimitGroupSectionProps = {
title: string
description?: string
source: RateLimitSource | null
meteredFeature?: string
}
function RateLimitGroupSection(props: RateLimitGroupSectionProps) {
const { t } = useTranslation()
const { fiveHourWindow, weeklyWindow } = resolveRateLimitWindows(props.source)
const statusBadge = getUsageStatusBadge(props.source?.rate_limit, t)
return (
<section className='bg-muted/40 flex flex-col gap-3 rounded-xl p-3'>
<SectionHeading title={props.title} description={props.description}>
{statusBadge}
</SectionHeading>
{props.meteredFeature ? (
<div className='bg-background ring-border/60 inline-flex max-w-full flex-wrap items-center gap-x-2 gap-y-1 rounded-lg px-2 py-1 text-xs ring-1'>
<span className='text-muted-foreground text-[11px]'>
metered_feature
</span>
<span className='min-w-0 font-mono break-all'>
{props.meteredFeature}
</span>
</div>
) : null}
<RateLimitWindowGrid
fiveHourWindow={fiveHourWindow}
weeklyWindow={weeklyWindow}
/>
</section>
)
}
function InfoField(props: {
label: string
value?: string | null
mono?: boolean
copyable?: boolean
className?: string
}) {
const { t } = useTranslation()
const { copyToClipboard, copiedText } = useCopyToClipboard({ notify: false })
const text = props.value?.trim() || ''
const hasCopied = copiedText === text
return (
<div
className={cn(
'bg-background ring-border/60 min-w-0 rounded-lg p-3 ring-1',
props.className
)}
>
<div className='text-muted-foreground text-[11px] font-medium'>
{props.label}
</div>
<div className='mt-1 flex min-w-0 items-start justify-between gap-2'>
<span
className={cn(
'min-w-0 flex-1 text-xs leading-5 break-all',
props.mono && 'font-mono tabular-nums'
)}
>
{text || '-'}
</span>
{props.copyable !== false && text ? (
<Button
type='button'
variant='ghost'
size='icon-xs'
aria-label={t('Copy')}
onClick={() => copyToClipboard(text)}
>
{hasCopied ? <Check className='text-success' /> : <Copy />}
</Button>
) : null}
</div>
</div>
)
}
function ResetCreditTimeField(props: {
label: string
value: string
emphasis?: boolean
}) {
return (
<div className='min-w-0'>
<div className='text-muted-foreground text-[11px] font-medium'>
{props.label}
</div>
<div
className={cn(
'mt-1 text-xs leading-5 tabular-nums',
props.emphasis ? 'font-semibold' : 'text-foreground'
)}
>
{props.value}
</div>
</div>
)
}
function ResetCreditItem(props: { credit: CodexResetCredit; index: number }) {
const { t } = useTranslation()
const statusBadge = getResetCreditStatusBadge(props.credit.status, t)
const title =
props.credit.title?.trim() || `${t('Reset Credit')} ${props.index + 1}`
const expiresIn = formatTimeLeftUntil(props.credit.expires_at, t)
const isAvailable =
normalizeResetCreditStatus(props.credit.status) === 'available'
return (
<div className='bg-background rounded-lg border p-3'>
<div className='flex flex-wrap items-start justify-between gap-3'>
<div className='min-w-0'>
<div className='flex flex-wrap items-center gap-2'>
<div className='min-w-0 text-sm font-medium break-words'>
{title}
</div>
<StatusBadge
label={t(statusBadge.label)}
variant={statusBadge.variant}
copyable={false}
/>
</div>
{props.credit.description ? (
<div className='text-muted-foreground mt-1 text-xs leading-5'>
{props.credit.description}
</div>
) : null}
{props.credit.id ? (
<div className='text-muted-foreground mt-1 font-mono text-[11px] break-all'>
{props.credit.id}
</div>
) : null}
</div>
<div className='shrink-0 text-right'>
<div className='text-muted-foreground text-[11px] font-medium'>
{t('Expires in')}
</div>
<div
className={cn(
'mt-1 text-sm font-semibold tabular-nums',
isAvailable ? 'text-success' : 'text-muted-foreground'
)}
>
{expiresIn}
</div>
</div>
</div>
<div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3'>
<ResetCreditTimeField
label={t('Granted at')}
value={formatIsoTimestamp(props.credit.granted_at)}
/>
<ResetCreditTimeField
label={t('Expires at')}
value={formatIsoTimestamp(props.credit.expires_at)}
/>
<ResetCreditTimeField
label={t('Redeemed at')}
value={formatIsoTimestamp(props.credit.redeemed_at)}
emphasis={Boolean(props.credit.redeemed_at)}
/>
</div>
</div>
)
}
function ResetCreditsPanel(props: {
payload: CodexResetCreditsPayload | null
response: CodexResetCreditsResponse | null
usageAvailableCount: string
isLoading: boolean
isResetting: boolean
errorMessage: string
resetErrorMessage: string
resetSuccessMessage: string
onRefresh: () => void
onRequestReset: () => void
}) {
const { t } = useTranslation()
const credits = useMemo(
() => sortResetCredits(props.payload?.credits ?? []),
[props.payload?.credits]
)
const detailAvailableCount = props.payload?.available_count
const availableCount = Number.isFinite(Number(detailAvailableCount))
? String(detailAvailableCount)
: props.usageAvailableCount
const totalEarnedCount = Number.isFinite(
Number(props.payload?.total_earned_count)
)
? String(props.payload?.total_earned_count)
: '-'
const canReset = Number(availableCount) > 0
let creditsContent: ReactNode
if (props.errorMessage) {
creditsContent = (
<div className='border-destructive/40 bg-destructive/10 text-destructive rounded-lg border px-3 py-2 text-sm'>
{props.errorMessage}
</div>
)
} else if (props.isLoading) {
creditsContent = (
<div className='flex flex-col gap-2'>
<Skeleton className='h-24 w-full' />
<Skeleton className='h-24 w-full' />
</div>
)
} else if (credits.length > 0) {
creditsContent = (
<div className='flex flex-col gap-2'>
{credits.map((credit, index) => (
<ResetCreditItem
key={
credit.id ??
credit.expires_at ??
credit.granted_at ??
credit.title ??
credit.reset_type ??
''
}
credit={credit}
index={index}
/>
))}
</div>
)
} else {
creditsContent = (
<Empty className='min-h-32 border'>
<EmptyHeader>
<EmptyTitle>{t('No reset credits')}</EmptyTitle>
<EmptyDescription>
{t('Upstream did not return reset credit details.')}
</EmptyDescription>
</EmptyHeader>
</Empty>
)
}
return (
<div className='flex flex-col gap-3 p-3'>
<div className='grid grid-cols-1 gap-3 sm:grid-cols-3'>
<InfoField
label={t('Available reset credits')}
value={availableCount}
mono
copyable={false}
/>
<InfoField
label={t('Total earned')}
value={totalEarnedCount}
mono
copyable={false}
/>
<InfoField
label='HTTP'
value={String(props.response?.upstream_status ?? '-')}
mono
copyable={false}
/>
</div>
<div className='flex flex-wrap items-center justify-between gap-2'>
<div className='text-muted-foreground text-xs leading-5'>
{t('Available credits are ordered by soonest expiration.')}
</div>
<Button
type='button'
variant='outline'
size='sm'
onClick={props.onRefresh}
disabled={props.isLoading}
>
<RefreshCw data-icon='inline-start' />
{t('Refresh details')}
</Button>
</div>
<div className='bg-muted/30 flex flex-col gap-3 rounded-lg border p-3 sm:flex-row sm:items-center sm:justify-between'>
<div className='min-w-0'>
<div className='text-sm font-semibold'>{t('Reset usage window')}</div>
<div className='text-muted-foreground mt-1 text-xs leading-5'>
{t(
'Use one available reset credit to refresh the current Codex usage windows.'
)}
</div>
</div>
<Button
type='button'
variant={canReset ? 'destructive' : 'outline'}
size='sm'
onClick={props.onRequestReset}
disabled={!canReset || props.isLoading || props.isResetting}
className='shrink-0'
>
<RotateCcw data-icon='inline-start' />
{props.isResetting ? t('Resetting...') : t('Apply reset')}
</Button>
</div>
{!canReset ? (
<Alert>
<AlertTriangle />
<AlertTitle>{t('No reset credits available')}</AlertTitle>
<AlertDescription>
{t('The reset request stays disabled until a credit is available.')}
</AlertDescription>
</Alert>
) : null}
{props.resetSuccessMessage ? (
<Alert className='border-success/40 bg-success/10 text-success'>
<Check />
<AlertTitle>{t('Reset completed')}</AlertTitle>
<AlertDescription>{props.resetSuccessMessage}</AlertDescription>
</Alert>
) : null}
{props.resetErrorMessage ? (
<Alert variant='destructive'>
<AlertTriangle />
<AlertTitle>{t('Reset failed')}</AlertTitle>
<AlertDescription>{props.resetErrorMessage}</AlertDescription>
</Alert>
) : null}
{creditsContent}
</div>
)
}
export function CodexUsageDialog({
open,
onOpenChange,
channelName,
channelId,
channelDisplayName,
channelDisplayId,
response,
onRefresh,
isRefreshing,
}: CodexUsageDialogProps) {
const { t } = useTranslation()
const { copiedText, copyToClipboard } = useCopyToClipboard({ notify: false })
const [showRawJson, setShowRawJson] = useState(false)
const [showResetCredits, setShowResetCredits] = useState(false)
const [resetCreditsResponse, setResetCreditsResponse] =
useState<CodexResetCreditsResponse | null>(null)
const [isLoadingResetCredits, setIsLoadingResetCredits] = useState(false)
const [resetCreditsError, setResetCreditsError] = useState('')
const [resetConfirmOpen, setResetConfirmOpen] = useState(false)
const [isResetting, setIsResetting] = useState(false)
const [resetActionError, setResetActionError] = useState('')
const [resetActionMessage, setResetActionMessage] = useState('')
const payload: CodexUsagePayload | null = useMemo(() => {
const raw = response?.data
if (!raw || typeof raw !== 'object') {
return null
}
return raw as CodexUsagePayload
}, [response?.data])
const resetCreditsPayload: CodexResetCreditsPayload | null = useMemo(() => {
const raw = resetCreditsResponse?.data
if (!raw || typeof raw !== 'object') {
return null
}
return raw as CodexResetCreditsPayload
}, [resetCreditsResponse?.data])
const rateLimit = payload?.rate_limit
const accountType = payload?.plan_type ?? rateLimit?.plan_type
const accountBadge = getAccountTypeBadge(accountType, t)
const additionalRateLimits = (payload?.additional_rate_limits ?? []).filter(
(item) => item && Object.keys(item).length > 0
)
const resetCredits =
resetCreditsPayload?.available_count ??
payload?.rate_limit_reset_credits?.available_count
const resetCreditsText = Number.isFinite(Number(resetCredits))
? String(resetCredits)
: '-'
const canResetCodexUsage = Number(resetCredits) > 0
const channelLabelName = channelDisplayName ?? channelName ?? '-'
let channelLabelId = ''
if (channelDisplayId != null) {
channelLabelId = ` (#${channelDisplayId})`
} else if (channelId) {
channelLabelId = ` (#${channelId})`
}
const channelLabel = `${channelLabelName}${channelLabelId}`
const { fiveHourWindow, weeklyWindow } = resolveRateLimitWindows(payload)
const errorMessage =
response?.success === false
? response?.message?.trim() || t('Failed to fetch usage')
: ''
const loadResetCredits = useCallback(
async (force = false) => {
if (!channelId) {
setResetCreditsError(t('Channel ID is required'))
return
}
if (isLoadingResetCredits || (!force && resetCreditsResponse)) {
return
}
setIsLoadingResetCredits(true)
setResetCreditsError('')
try {
const res = await getCodexResetCredits(channelId)
if (!res.success) {
throw new Error(
res.message || t('Failed to fetch reset credit details')
)
}
setResetCreditsResponse(res)
} catch (error) {
setResetCreditsError(
error instanceof Error
? error.message
: t('Failed to fetch reset credit details')
)
} finally {
setIsLoadingResetCredits(false)
}
},