CodexUsageModal.jsx 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import React, { useCallback, useEffect, useRef, useState } from 'react';
  16. import { Modal, Button, Progress, Tag, Typography, Spin } from '@douyinfe/semi-ui';
  17. import { API, showError } from '../../../../helpers';
  18. const { Text } = Typography;
  19. const clampPercent = (value) => {
  20. const v = Number(value);
  21. if (!Number.isFinite(v)) return 0;
  22. return Math.max(0, Math.min(100, v));
  23. };
  24. const pickStrokeColor = (percent) => {
  25. const p = clampPercent(percent);
  26. if (p >= 95) return '#ef4444';
  27. if (p >= 80) return '#f59e0b';
  28. return '#3b82f6';
  29. };
  30. const formatDurationSeconds = (seconds, t) => {
  31. const tt = typeof t === 'function' ? t : (v) => v;
  32. const s = Number(seconds);
  33. if (!Number.isFinite(s) || s <= 0) return '-';
  34. const total = Math.floor(s);
  35. const hours = Math.floor(total / 3600);
  36. const minutes = Math.floor((total % 3600) / 60);
  37. const secs = total % 60;
  38. if (hours > 0) return `${hours}${tt('小时')} ${minutes}${tt('分钟')}`;
  39. if (minutes > 0) return `${minutes}${tt('分钟')} ${secs}${tt('秒')}`;
  40. return `${secs}${tt('秒')}`;
  41. };
  42. const formatUnixSeconds = (unixSeconds) => {
  43. const v = Number(unixSeconds);
  44. if (!Number.isFinite(v) || v <= 0) return '-';
  45. try {
  46. return new Date(v * 1000).toLocaleString();
  47. } catch (error) {
  48. return String(unixSeconds);
  49. }
  50. };
  51. const RateLimitWindowCard = ({ t, title, windowData }) => {
  52. const tt = typeof t === 'function' ? t : (v) => v;
  53. const percent = clampPercent(windowData?.used_percent ?? 0);
  54. const resetAt = windowData?.reset_at;
  55. const resetAfterSeconds = windowData?.reset_after_seconds;
  56. const limitWindowSeconds = windowData?.limit_window_seconds;
  57. return (
  58. <div className='rounded-lg border border-semi-color-border bg-semi-color-bg-0 p-3'>
  59. <div className='flex items-center justify-between gap-2'>
  60. <div className='font-medium'>{title}</div>
  61. <Text type='tertiary' size='small'>
  62. {tt('重置时间:')}
  63. {formatUnixSeconds(resetAt)}
  64. </Text>
  65. </div>
  66. <div className='mt-2'>
  67. <Progress
  68. percent={percent}
  69. stroke={pickStrokeColor(percent)}
  70. showInfo={true}
  71. />
  72. </div>
  73. <div className='mt-1 flex flex-wrap items-center gap-2 text-xs text-semi-color-text-2'>
  74. <div>
  75. {tt('已使用:')}
  76. {percent}%
  77. </div>
  78. <div>
  79. {tt('距离重置:')}
  80. {formatDurationSeconds(resetAfterSeconds, tt)}
  81. </div>
  82. <div>
  83. {tt('窗口:')}
  84. {formatDurationSeconds(limitWindowSeconds, tt)}
  85. </div>
  86. </div>
  87. </div>
  88. );
  89. };
  90. const CodexUsageView = ({ t, record, payload, onCopy, onRefresh }) => {
  91. const tt = typeof t === 'function' ? t : (v) => v;
  92. const data = payload?.data ?? null;
  93. const rateLimit = data?.rate_limit ?? {};
  94. const primary = rateLimit?.primary_window ?? null;
  95. const secondary = rateLimit?.secondary_window ?? null;
  96. const allowed = !!rateLimit?.allowed;
  97. const limitReached = !!rateLimit?.limit_reached;
  98. const upstreamStatus = payload?.upstream_status;
  99. const statusTag =
  100. allowed && !limitReached ? (
  101. <Tag color='green'>{tt('可用')}</Tag>
  102. ) : (
  103. <Tag color='red'>{tt('受限')}</Tag>
  104. );
  105. const rawText =
  106. typeof data === 'string' ? data : JSON.stringify(data ?? payload, null, 2);
  107. return (
  108. <div className='flex flex-col gap-3'>
  109. <div className='flex flex-wrap items-center justify-between gap-2'>
  110. <Text type='tertiary' size='small'>
  111. {tt('渠道:')}
  112. {record?.name || '-'} ({tt('编号:')}
  113. {record?.id || '-'})
  114. </Text>
  115. <div className='flex items-center gap-2'>
  116. {statusTag}
  117. <Button size='small' type='tertiary' theme='borderless' onClick={onRefresh}>
  118. {tt('刷新')}
  119. </Button>
  120. </div>
  121. </div>
  122. <div className='flex flex-wrap items-center justify-between gap-2'>
  123. <Text type='tertiary' size='small'>
  124. {tt('上游状态码:')}
  125. {upstreamStatus ?? '-'}
  126. </Text>
  127. </div>
  128. <div className='grid grid-cols-1 gap-3 md:grid-cols-2'>
  129. <RateLimitWindowCard
  130. t={tt}
  131. title={tt('5小时窗口')}
  132. windowData={primary}
  133. />
  134. <RateLimitWindowCard
  135. t={tt}
  136. title={tt('每周窗口')}
  137. windowData={secondary}
  138. />
  139. </div>
  140. <div>
  141. <div className='mb-1 flex items-center justify-between gap-2'>
  142. <div className='text-sm font-medium'>{tt('原始 JSON')}</div>
  143. <Button
  144. size='small'
  145. type='primary'
  146. theme='outline'
  147. onClick={() => onCopy?.(rawText)}
  148. disabled={!rawText}
  149. >
  150. {tt('复制')}
  151. </Button>
  152. </div>
  153. <pre className='max-h-[50vh] overflow-auto rounded-lg bg-semi-color-fill-0 p-3 text-xs text-semi-color-text-0'>
  154. {rawText}
  155. </pre>
  156. </div>
  157. </div>
  158. );
  159. };
  160. const CodexUsageLoader = ({ t, record, initialPayload, onCopy }) => {
  161. const tt = typeof t === 'function' ? t : (v) => v;
  162. const [loading, setLoading] = useState(!initialPayload);
  163. const [payload, setPayload] = useState(initialPayload ?? null);
  164. const hasShownErrorRef = useRef(false);
  165. const mountedRef = useRef(true);
  166. const recordId = record?.id;
  167. const fetchUsage = useCallback(async () => {
  168. if (!recordId) {
  169. if (mountedRef.current) setPayload(null);
  170. return;
  171. }
  172. if (mountedRef.current) setLoading(true);
  173. try {
  174. const res = await API.get(`/api/channel/${recordId}/codex/usage`, {
  175. skipErrorHandler: true,
  176. });
  177. if (!mountedRef.current) return;
  178. setPayload(res?.data ?? null);
  179. if (!res?.data?.success && !hasShownErrorRef.current) {
  180. hasShownErrorRef.current = true;
  181. showError(tt('获取用量失败'));
  182. }
  183. } catch (error) {
  184. if (!mountedRef.current) return;
  185. if (!hasShownErrorRef.current) {
  186. hasShownErrorRef.current = true;
  187. showError(tt('获取用量失败'));
  188. }
  189. setPayload({ success: false, message: String(error) });
  190. } finally {
  191. if (mountedRef.current) setLoading(false);
  192. }
  193. }, [recordId, tt]);
  194. useEffect(() => {
  195. mountedRef.current = true;
  196. return () => {
  197. mountedRef.current = false;
  198. };
  199. }, []);
  200. useEffect(() => {
  201. if (initialPayload) return;
  202. fetchUsage().catch(() => {});
  203. }, [fetchUsage, initialPayload]);
  204. if (loading) {
  205. return (
  206. <div className='flex items-center justify-center py-10'>
  207. <Spin spinning={true} size='large' tip={tt('加载中...')} />
  208. </div>
  209. );
  210. }
  211. if (!payload) {
  212. return (
  213. <div className='flex flex-col gap-3'>
  214. <Text type='danger'>{tt('获取用量失败')}</Text>
  215. <div className='flex justify-end'>
  216. <Button size='small' type='primary' theme='outline' onClick={fetchUsage}>
  217. {tt('刷新')}
  218. </Button>
  219. </div>
  220. </div>
  221. );
  222. }
  223. return (
  224. <CodexUsageView
  225. t={tt}
  226. record={record}
  227. payload={payload}
  228. onCopy={onCopy}
  229. onRefresh={fetchUsage}
  230. />
  231. );
  232. };
  233. export const openCodexUsageModal = ({ t, record, payload, onCopy }) => {
  234. const tt = typeof t === 'function' ? t : (v) => v;
  235. Modal.info({
  236. title: tt('Codex 用量'),
  237. centered: true,
  238. width: 900,
  239. style: { maxWidth: '95vw' },
  240. content: (
  241. <CodexUsageLoader
  242. t={tt}
  243. record={record}
  244. initialPayload={payload}
  245. onCopy={onCopy}
  246. />
  247. ),
  248. footer: (
  249. <div className='flex justify-end gap-2'>
  250. <Button type='primary' theme='solid' onClick={() => Modal.destroyAll()}>
  251. {tt('关闭')}
  252. </Button>
  253. </div>
  254. ),
  255. });
  256. };