mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-23 08:00:49 +00:00
refactor(frontend): simplify client architecture
Remove frontend schemas and tests, keep API modules as thin GET/POST adapters, and replace manual SSE and browser helpers with existing VueUse and utility primitives. Reorganize feature helpers, move unauthorized handling into an app plugin, align the admin key removal route, and satisfy the enabled accessibility rules. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -46,7 +46,7 @@ pub fn router() -> Router<AppState> {
|
||||
.route("/api/admin/settings", get(settings).post(update_settings))
|
||||
.route(
|
||||
"/api/admin/settings/admin-api-key",
|
||||
get(admin_api_key_status).delete(delete_admin_api_key),
|
||||
get(admin_api_key_status).post(delete_admin_api_key),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/settings/admin-api-key/regenerate",
|
||||
|
||||
@@ -115,7 +115,7 @@ pub(crate) async fn regenerate_admin_api_key(
|
||||
))
|
||||
}
|
||||
|
||||
/// `DELETE /api/admin/settings/admin-api-key`
|
||||
/// `POST /api/admin/settings/admin-api-key`
|
||||
pub(crate) async fn delete_admin_api_key(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
|
||||
@@ -209,7 +209,7 @@ async fn admin_settings_admin_api_key_should_delete_and_revoke_access() {
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("DELETE")
|
||||
.method("POST")
|
||||
.uri("/api/admin/settings/admin-api-key")
|
||||
.header("cookie", "cpr_admin_session=session_1")
|
||||
.header("x-request-id", "req_settings_admin_key_delete")
|
||||
|
||||
@@ -513,13 +513,13 @@ Vue 管理端位于 `frontend/src`,使用 Vue Router、Pinia 和按领域划
|
||||
```text
|
||||
view / component
|
||||
-> feature composable / explicit Pinia store
|
||||
-> api module / api stream adapter
|
||||
-> request transport
|
||||
-> api module -> request transport
|
||||
-> VueUse SSE
|
||||
```
|
||||
|
||||
- `api/request.ts` 返回 `unknown`,endpoint module 使用 Zod 在 HTTP 边界解析;不使用类型断言代替运行时校验。
|
||||
- `api/request.ts` 只负责请求与管理端 envelope 解包;endpoint module 不声明响应 DTO,直接透传 `data` / `params`,管理端写操作统一使用 `POST`。
|
||||
- 401 处理由 `main.ts` 注入,request transport 不依赖 router 或 store。
|
||||
- EventSource、URL 和事件解析只存在于 `api/streams`;feature 只消费 typed event 和可关闭 stream handle。
|
||||
- SSE 由对应 feature composable / Pinia store 使用 VueUse `useEventSource` 管理,连接随 feature 生命周期关闭,不保留手写 `api/streams` transport。
|
||||
- 账号、API Key、usage 列表使用 latest-request-wins 的 `usePagedQuery`,页内选择统一由 `usePageSelection` 管理。
|
||||
- system update 是 layout 持有的单例 Pinia 状态;桌面和移动 Sidebar 只发出打开意图,不挂载或清理共享 stream。
|
||||
- API 结果、composable 返回值和局部 view model 默认依赖 TypeScript 推导;显式类型只用于 Props/Emits、领域判别联合和可复用泛型边界。
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import antfu from '@antfu/eslint-config'
|
||||
|
||||
export default antfu(
|
||||
{
|
||||
type: 'app',
|
||||
ignores: ['dist', 'coverage', 'pnpm-workspace.yaml'],
|
||||
formatters: {
|
||||
css: true,
|
||||
html: true,
|
||||
markdown: 'prettier',
|
||||
},
|
||||
stylistic: {
|
||||
indent: 2,
|
||||
quotes: 'single',
|
||||
},
|
||||
typescript: true,
|
||||
vue: {
|
||||
a11y: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
'ts/no-use-before-define': 'off',
|
||||
'vue/custom-event-name-casing': 'off',
|
||||
'vue/no-unused-refs': 'off',
|
||||
'vue-a11y/click-events-have-key-events': 'off',
|
||||
'vue-a11y/label-has-for': 'off',
|
||||
'vue-a11y/mouse-events-have-key-events': 'off',
|
||||
'vue-a11y/no-redundant-roles': 'off',
|
||||
'vue-a11y/no-static-element-interactions': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/api/**/*.ts'],
|
||||
rules: {
|
||||
'no-restricted-imports': [
|
||||
'error',
|
||||
{
|
||||
patterns: [
|
||||
{
|
||||
group: ['@/layout/**', '@/router/**', '@/stores/**', '@/views/**'],
|
||||
message: 'API transport 和 adapter 不能反向依赖 UI、路由或状态层。',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/composables/**/*.ts', 'src/layout/**/*.vue', 'src/stores/**/*.ts', 'src/views/**'],
|
||||
rules: {
|
||||
'no-restricted-imports': [
|
||||
'error',
|
||||
{
|
||||
paths: [
|
||||
{
|
||||
name: 'axios',
|
||||
message: 'HTTP transport 只能由 src/api 持有。',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
import antfu from '@antfu/eslint-config'
|
||||
|
||||
export default antfu(
|
||||
{
|
||||
type: 'app',
|
||||
ignores: ['dist', 'coverage', 'pnpm-workspace.yaml'],
|
||||
formatters: {
|
||||
css: true,
|
||||
html: true,
|
||||
markdown: 'prettier',
|
||||
},
|
||||
stylistic: {
|
||||
indent: 2,
|
||||
quotes: 'single',
|
||||
},
|
||||
typescript: true,
|
||||
vue: {
|
||||
a11y: true,
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -10,8 +10,7 @@
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"format": "pnpm run lint:fix",
|
||||
"format:check": "pnpm run lint",
|
||||
"test": "vitest run"
|
||||
"format:check": "pnpm run lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.2.8",
|
||||
@@ -28,8 +27,7 @@
|
||||
"pinia": "^3.0.4",
|
||||
"pinia-plugin-persistedstate": "^4.7.1",
|
||||
"vue": "^3.5.39",
|
||||
"vue-router": "^5.1.0",
|
||||
"zod": "^4.4.3"
|
||||
"vue-router": "^5.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^9.1.0",
|
||||
@@ -43,7 +41,6 @@
|
||||
"tailwindcss": "^4.3.2",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.1.4",
|
||||
"vitest": "^4.1.10",
|
||||
"vue-tsc": "^3.3.7"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+5
-250
@@ -1,7 +1,7 @@
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
autoInstallPeers: false
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
@@ -53,13 +53,10 @@ importers:
|
||||
vue-router:
|
||||
specifier: ^5.1.0
|
||||
version: 5.1.0(@vue/compiler-sfc@3.5.39)(pinia@3.0.4(typescript@6.0.3)(vue@3.5.39(typescript@6.0.3)))(rolldown@1.1.5)(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.39(typescript@6.0.3))
|
||||
zod:
|
||||
specifier: ^4.4.3
|
||||
version: 4.4.3
|
||||
devDependencies:
|
||||
'@antfu/eslint-config':
|
||||
specifier: ^9.1.0
|
||||
version: 9.1.0(@typescript-eslint/typescript-estree@8.64.0(typescript@6.0.3))(@typescript-eslint/utils@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(@vue/compiler-sfc@3.5.39)(eslint-plugin-format@2.0.1(eslint@10.7.0(jiti@2.7.0)))(eslint-plugin-vuejs-accessibility@2.5.0(eslint@10.7.0(jiti@2.7.0))(globals@17.7.0))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)(vitest@4.1.10(@types/node@26.1.1)(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)))
|
||||
version: 9.1.0(@typescript-eslint/typescript-estree@8.64.0(typescript@6.0.3))(@typescript-eslint/utils@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(@vue/compiler-sfc@3.5.39)(eslint-plugin-format@2.0.1(eslint@10.7.0(jiti@2.7.0)))(eslint-plugin-vuejs-accessibility@2.5.0(eslint@10.7.0(jiti@2.7.0))(globals@17.7.0))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.3.2
|
||||
version: 4.3.2(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0))
|
||||
@@ -90,9 +87,6 @@ importers:
|
||||
vite:
|
||||
specifier: ^8.1.4
|
||||
version: 8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)
|
||||
vitest:
|
||||
specifier: ^4.1.10
|
||||
version: 4.1.10(@types/node@26.1.1)(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0))
|
||||
vue-tsc:
|
||||
specifier: ^3.3.7
|
||||
version: 3.3.7(typescript@6.0.3)
|
||||
@@ -587,9 +581,6 @@ packages:
|
||||
resolution: {integrity: sha512-TeheYy0ILzBEI/CO55CP6zJCSdSWeRtGnHy8U8dWSUH4I68iqTsy7HkMktR4xakThc9jotkPQUXT4ITdbV7cHA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
'@standard-schema/spec@1.1.0':
|
||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||
|
||||
'@stylistic/eslint-plugin@5.10.0':
|
||||
resolution: {integrity: sha512-nPK52ZHvot8Ju/0A4ucSX1dcPV2/1clx0kLcH5wDmrE4naKso7TUC/voUyU1O9OTKTrR6MYip6LP0ogEMQ9jPQ==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
@@ -693,15 +684,9 @@ packages:
|
||||
'@tybys/wasm-util@0.10.3':
|
||||
resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
|
||||
|
||||
'@types/chai@5.2.3':
|
||||
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
||||
|
||||
'@types/debug@4.1.13':
|
||||
resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}
|
||||
|
||||
'@types/deep-eql@4.0.2':
|
||||
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
|
||||
|
||||
'@types/esrecurse@4.3.1':
|
||||
resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==}
|
||||
|
||||
@@ -820,35 +805,6 @@ packages:
|
||||
vitest:
|
||||
optional: true
|
||||
|
||||
'@vitest/expect@4.1.10':
|
||||
resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==}
|
||||
|
||||
'@vitest/mocker@4.1.10':
|
||||
resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==}
|
||||
peerDependencies:
|
||||
msw: ^2.4.9
|
||||
vite: ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
peerDependenciesMeta:
|
||||
msw:
|
||||
optional: true
|
||||
vite:
|
||||
optional: true
|
||||
|
||||
'@vitest/pretty-format@4.1.10':
|
||||
resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==}
|
||||
|
||||
'@vitest/runner@4.1.10':
|
||||
resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==}
|
||||
|
||||
'@vitest/snapshot@4.1.10':
|
||||
resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==}
|
||||
|
||||
'@vitest/spy@4.1.10':
|
||||
resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==}
|
||||
|
||||
'@vitest/utils@4.1.10':
|
||||
resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==}
|
||||
|
||||
'@volar/language-core@2.4.28':
|
||||
resolution: {integrity: sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==}
|
||||
|
||||
@@ -973,10 +929,6 @@ packages:
|
||||
resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
assertion-error@2.0.1:
|
||||
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
ast-kit@2.2.0:
|
||||
resolution: {integrity: sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==}
|
||||
engines: {node: '>=20.19.0'}
|
||||
@@ -1033,10 +985,6 @@ packages:
|
||||
ccount@2.0.1:
|
||||
resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
|
||||
|
||||
chai@6.2.2:
|
||||
resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
change-case@5.4.4:
|
||||
resolution: {integrity: sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==}
|
||||
|
||||
@@ -1069,9 +1017,6 @@ packages:
|
||||
confbox@0.2.4:
|
||||
resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==}
|
||||
|
||||
convert-source-map@2.0.0:
|
||||
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
|
||||
|
||||
copy-anything@4.0.5:
|
||||
resolution: {integrity: sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -1168,9 +1113,6 @@ packages:
|
||||
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
es-module-lexer@2.3.1:
|
||||
resolution: {integrity: sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==}
|
||||
|
||||
es-object-atoms@1.1.2:
|
||||
resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -1410,17 +1352,10 @@ packages:
|
||||
estree-walker@2.0.2:
|
||||
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
|
||||
|
||||
estree-walker@3.0.3:
|
||||
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
|
||||
|
||||
esutils@2.0.3:
|
||||
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
expect-type@1.4.0:
|
||||
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
exsolve@1.1.0:
|
||||
resolution: {integrity: sha512-D+42+T12DdIlJM3uepa55qGiL3sYdLBOxIl2ifQCzCHz4c7eiolaHsi3BIqEr7JxBzxv2pYZQX9kw16ziMcEmw==}
|
||||
|
||||
@@ -1921,10 +1856,6 @@ packages:
|
||||
object-deep-merge@2.0.1:
|
||||
resolution: {integrity: sha512-aKttDKcU3pyZqKcCkDhsMn70WmZFG2JGDQLP9EcLyTSIFQRCPWLAmBZRLJnrVUrhPG1jETEEbfdgbNtJf1LyMg==}
|
||||
|
||||
obug@2.1.3:
|
||||
resolution: {integrity: sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
|
||||
ohash@2.0.11:
|
||||
resolution: {integrity: sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==}
|
||||
|
||||
@@ -2108,9 +2039,6 @@ packages:
|
||||
resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
siginfo@2.0.0:
|
||||
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
|
||||
|
||||
sisteransi@1.0.5:
|
||||
resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}
|
||||
|
||||
@@ -2131,12 +2059,6 @@ packages:
|
||||
resolution: {integrity: sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
stackback@0.0.2:
|
||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||
|
||||
std-env@4.2.0:
|
||||
resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}
|
||||
|
||||
strip-indent@4.1.1:
|
||||
resolution: {integrity: sha512-SlyRoSkdh1dYP0PzclLE7r0M9sgbFKKMFXpFRUMNuKhQSbC6VQIGzq3E0qsfvGJaUFJPGv6Ws1NZ/haTAjfbMA==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -2156,9 +2078,6 @@ packages:
|
||||
resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
tinybench@2.9.0:
|
||||
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
||||
|
||||
tinyexec@1.2.4:
|
||||
resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -2171,10 +2090,6 @@ packages:
|
||||
resolution: {integrity: sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==}
|
||||
engines: {node: ^20.0.0 || >=22.0.0}
|
||||
|
||||
tinyrainbow@3.1.0:
|
||||
resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
|
||||
to-valid-identifier@1.0.0:
|
||||
resolution: {integrity: sha512-41wJyvKep3yT2tyPqX/4blcfybknGB4D+oETKLs7Q76UiPqRpUJK3hr1nxelyYO0PHKVzJwlu0aCeEAsGI6rpw==}
|
||||
engines: {node: '>=20'}
|
||||
@@ -2317,47 +2232,6 @@ packages:
|
||||
yaml:
|
||||
optional: true
|
||||
|
||||
vitest@4.1.10:
|
||||
resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==}
|
||||
engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@edge-runtime/vm': '*'
|
||||
'@opentelemetry/api': ^1.9.0
|
||||
'@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
|
||||
'@vitest/browser-playwright': 4.1.10
|
||||
'@vitest/browser-preview': 4.1.10
|
||||
'@vitest/browser-webdriverio': 4.1.10
|
||||
'@vitest/coverage-istanbul': 4.1.10
|
||||
'@vitest/coverage-v8': 4.1.10
|
||||
'@vitest/ui': 4.1.10
|
||||
happy-dom: '*'
|
||||
jsdom: '*'
|
||||
vite: ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
peerDependenciesMeta:
|
||||
'@edge-runtime/vm':
|
||||
optional: true
|
||||
'@opentelemetry/api':
|
||||
optional: true
|
||||
'@types/node':
|
||||
optional: true
|
||||
'@vitest/browser-playwright':
|
||||
optional: true
|
||||
'@vitest/browser-preview':
|
||||
optional: true
|
||||
'@vitest/browser-webdriverio':
|
||||
optional: true
|
||||
'@vitest/coverage-istanbul':
|
||||
optional: true
|
||||
'@vitest/coverage-v8':
|
||||
optional: true
|
||||
'@vitest/ui':
|
||||
optional: true
|
||||
happy-dom:
|
||||
optional: true
|
||||
jsdom:
|
||||
optional: true
|
||||
|
||||
vscode-uri@3.1.0:
|
||||
resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}
|
||||
|
||||
@@ -2407,11 +2281,6 @@ packages:
|
||||
engines: {node: '>= 8'}
|
||||
hasBin: true
|
||||
|
||||
why-is-node-running@2.3.0:
|
||||
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
|
||||
engines: {node: '>=8'}
|
||||
hasBin: true
|
||||
|
||||
word-wrap@1.2.5:
|
||||
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
@@ -2433,9 +2302,6 @@ packages:
|
||||
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
zod@4.4.3:
|
||||
resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
|
||||
|
||||
zrender@6.1.0:
|
||||
resolution: {integrity: sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==}
|
||||
|
||||
@@ -2444,7 +2310,7 @@ packages:
|
||||
|
||||
snapshots:
|
||||
|
||||
'@antfu/eslint-config@9.1.0(@typescript-eslint/typescript-estree@8.64.0(typescript@6.0.3))(@typescript-eslint/utils@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(@vue/compiler-sfc@3.5.39)(eslint-plugin-format@2.0.1(eslint@10.7.0(jiti@2.7.0)))(eslint-plugin-vuejs-accessibility@2.5.0(eslint@10.7.0(jiti@2.7.0))(globals@17.7.0))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)(vitest@4.1.10(@types/node@26.1.1)(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)))':
|
||||
'@antfu/eslint-config@9.1.0(@typescript-eslint/typescript-estree@8.64.0(typescript@6.0.3))(@typescript-eslint/utils@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(@vue/compiler-sfc@3.5.39)(eslint-plugin-format@2.0.1(eslint@10.7.0(jiti@2.7.0)))(eslint-plugin-vuejs-accessibility@2.5.0(eslint@10.7.0(jiti@2.7.0))(globals@17.7.0))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)':
|
||||
dependencies:
|
||||
'@antfu/install-pkg': 1.1.0
|
||||
'@clack/prompts': 1.7.0
|
||||
@@ -2454,7 +2320,7 @@ snapshots:
|
||||
'@stylistic/eslint-plugin': 5.10.0(eslint@10.7.0(jiti@2.7.0))
|
||||
'@typescript-eslint/eslint-plugin': 8.64.0(@typescript-eslint/parser@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)
|
||||
'@typescript-eslint/parser': 8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)
|
||||
'@vitest/eslint-plugin': 1.6.23(@typescript-eslint/eslint-plugin@8.64.0(@typescript-eslint/parser@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)(vitest@4.1.10(@types/node@26.1.1)(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)))
|
||||
'@vitest/eslint-plugin': 1.6.23(@typescript-eslint/eslint-plugin@8.64.0(@typescript-eslint/parser@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)
|
||||
ansis: 4.3.1
|
||||
cac: 7.0.0
|
||||
eslint: 10.7.0(jiti@2.7.0)
|
||||
@@ -2817,8 +2683,6 @@ snapshots:
|
||||
|
||||
'@sindresorhus/base62@1.0.0': {}
|
||||
|
||||
'@standard-schema/spec@1.1.0': {}
|
||||
|
||||
'@stylistic/eslint-plugin@5.10.0(eslint@10.7.0(jiti@2.7.0))':
|
||||
dependencies:
|
||||
'@eslint-community/eslint-utils': 4.9.1(eslint@10.7.0(jiti@2.7.0))
|
||||
@@ -2902,17 +2766,10 @@ snapshots:
|
||||
tslib: 2.8.1
|
||||
optional: true
|
||||
|
||||
'@types/chai@5.2.3':
|
||||
dependencies:
|
||||
'@types/deep-eql': 4.0.2
|
||||
assertion-error: 2.0.1
|
||||
|
||||
'@types/debug@4.1.13':
|
||||
dependencies:
|
||||
'@types/ms': 2.1.0
|
||||
|
||||
'@types/deep-eql@4.0.2': {}
|
||||
|
||||
'@types/esrecurse@4.3.1': {}
|
||||
|
||||
'@types/estree@1.0.9': {}
|
||||
@@ -3041,7 +2898,7 @@ snapshots:
|
||||
vite: 8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)
|
||||
vue: 3.5.39(typescript@6.0.3)
|
||||
|
||||
'@vitest/eslint-plugin@1.6.23(@typescript-eslint/eslint-plugin@8.64.0(@typescript-eslint/parser@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)(vitest@4.1.10(@types/node@26.1.1)(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)))':
|
||||
'@vitest/eslint-plugin@1.6.23(@typescript-eslint/eslint-plugin@8.64.0(@typescript-eslint/parser@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)':
|
||||
dependencies:
|
||||
'@typescript-eslint/scope-manager': 8.64.0
|
||||
'@typescript-eslint/utils': 8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)
|
||||
@@ -3049,51 +2906,9 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@typescript-eslint/eslint-plugin': 8.64.0(@typescript-eslint/parser@8.64.0(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.7.0(jiti@2.7.0))(typescript@6.0.3)
|
||||
typescript: 6.0.3
|
||||
vitest: 4.1.10(@types/node@26.1.1)(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0))
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@vitest/expect@4.1.10':
|
||||
dependencies:
|
||||
'@standard-schema/spec': 1.1.0
|
||||
'@types/chai': 5.2.3
|
||||
'@vitest/spy': 4.1.10
|
||||
'@vitest/utils': 4.1.10
|
||||
chai: 6.2.2
|
||||
tinyrainbow: 3.1.0
|
||||
|
||||
'@vitest/mocker@4.1.10(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0))':
|
||||
dependencies:
|
||||
'@vitest/spy': 4.1.10
|
||||
estree-walker: 3.0.3
|
||||
magic-string: 0.30.21
|
||||
optionalDependencies:
|
||||
vite: 8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)
|
||||
|
||||
'@vitest/pretty-format@4.1.10':
|
||||
dependencies:
|
||||
tinyrainbow: 3.1.0
|
||||
|
||||
'@vitest/runner@4.1.10':
|
||||
dependencies:
|
||||
'@vitest/utils': 4.1.10
|
||||
pathe: 2.0.3
|
||||
|
||||
'@vitest/snapshot@4.1.10':
|
||||
dependencies:
|
||||
'@vitest/pretty-format': 4.1.10
|
||||
'@vitest/utils': 4.1.10
|
||||
magic-string: 0.30.21
|
||||
pathe: 2.0.3
|
||||
|
||||
'@vitest/spy@4.1.10': {}
|
||||
|
||||
'@vitest/utils@4.1.10':
|
||||
dependencies:
|
||||
'@vitest/pretty-format': 4.1.10
|
||||
convert-source-map: 2.0.0
|
||||
tinyrainbow: 3.1.0
|
||||
|
||||
'@volar/language-core@2.4.28':
|
||||
dependencies:
|
||||
'@volar/source-map': 2.4.28
|
||||
@@ -3256,8 +3071,6 @@ snapshots:
|
||||
|
||||
aria-query@5.3.2: {}
|
||||
|
||||
assertion-error@2.0.1: {}
|
||||
|
||||
ast-kit@2.2.0:
|
||||
dependencies:
|
||||
'@babel/parser': 7.29.7
|
||||
@@ -3314,8 +3127,6 @@ snapshots:
|
||||
|
||||
ccount@2.0.1: {}
|
||||
|
||||
chai@6.2.2: {}
|
||||
|
||||
change-case@5.4.4: {}
|
||||
|
||||
character-entities@2.0.2: {}
|
||||
@@ -3338,8 +3149,6 @@ snapshots:
|
||||
|
||||
confbox@0.2.4: {}
|
||||
|
||||
convert-source-map@2.0.0: {}
|
||||
|
||||
copy-anything@4.0.5:
|
||||
dependencies:
|
||||
is-what: 5.5.0
|
||||
@@ -3416,8 +3225,6 @@ snapshots:
|
||||
|
||||
es-errors@1.3.0: {}
|
||||
|
||||
es-module-lexer@2.3.1: {}
|
||||
|
||||
es-object-atoms@1.1.2:
|
||||
dependencies:
|
||||
es-errors: 1.3.0
|
||||
@@ -3736,14 +3543,8 @@ snapshots:
|
||||
|
||||
estree-walker@2.0.2: {}
|
||||
|
||||
estree-walker@3.0.3:
|
||||
dependencies:
|
||||
'@types/estree': 1.0.9
|
||||
|
||||
esutils@2.0.3: {}
|
||||
|
||||
expect-type@1.4.0: {}
|
||||
|
||||
exsolve@1.1.0: {}
|
||||
|
||||
fast-deep-equal@3.1.3: {}
|
||||
@@ -4370,8 +4171,6 @@ snapshots:
|
||||
|
||||
object-deep-merge@2.0.1: {}
|
||||
|
||||
obug@2.1.3: {}
|
||||
|
||||
ohash@2.0.11: {}
|
||||
|
||||
optionator@0.9.4:
|
||||
@@ -4557,8 +4356,6 @@ snapshots:
|
||||
|
||||
shebang-regex@3.0.0: {}
|
||||
|
||||
siginfo@2.0.0: {}
|
||||
|
||||
sisteransi@1.0.5: {}
|
||||
|
||||
source-map-js@1.2.1: {}
|
||||
@@ -4574,10 +4371,6 @@ snapshots:
|
||||
|
||||
speakingurl@14.0.1: {}
|
||||
|
||||
stackback@0.0.2: {}
|
||||
|
||||
std-env@4.2.0: {}
|
||||
|
||||
strip-indent@4.1.1: {}
|
||||
|
||||
superjson@2.2.6:
|
||||
@@ -4592,8 +4385,6 @@ snapshots:
|
||||
|
||||
tapable@2.3.3: {}
|
||||
|
||||
tinybench@2.9.0: {}
|
||||
|
||||
tinyexec@1.2.4: {}
|
||||
|
||||
tinyglobby@0.2.17:
|
||||
@@ -4603,8 +4394,6 @@ snapshots:
|
||||
|
||||
tinypool@2.1.0: {}
|
||||
|
||||
tinyrainbow@3.1.0: {}
|
||||
|
||||
to-valid-identifier@1.0.0:
|
||||
dependencies:
|
||||
'@sindresorhus/base62': 1.0.0
|
||||
@@ -4696,33 +4485,6 @@ snapshots:
|
||||
jiti: 2.7.0
|
||||
yaml: 2.9.0
|
||||
|
||||
vitest@4.1.10(@types/node@26.1.1)(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)):
|
||||
dependencies:
|
||||
'@vitest/expect': 4.1.10
|
||||
'@vitest/mocker': 4.1.10(vite@8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0))
|
||||
'@vitest/pretty-format': 4.1.10
|
||||
'@vitest/runner': 4.1.10
|
||||
'@vitest/snapshot': 4.1.10
|
||||
'@vitest/spy': 4.1.10
|
||||
'@vitest/utils': 4.1.10
|
||||
es-module-lexer: 2.3.1
|
||||
expect-type: 1.4.0
|
||||
magic-string: 0.30.21
|
||||
obug: 2.1.3
|
||||
pathe: 2.0.3
|
||||
picomatch: 4.0.5
|
||||
std-env: 4.2.0
|
||||
tinybench: 2.9.0
|
||||
tinyexec: 1.2.4
|
||||
tinyglobby: 0.2.17
|
||||
tinyrainbow: 3.1.0
|
||||
vite: 8.1.4(@types/node@26.1.1)(jiti@2.7.0)(yaml@2.9.0)
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 26.1.1
|
||||
transitivePeerDependencies:
|
||||
- msw
|
||||
|
||||
vscode-uri@3.1.0: {}
|
||||
|
||||
vue-eslint-parser@10.4.1(eslint@10.7.0(jiti@2.7.0)):
|
||||
@@ -4793,11 +4555,6 @@ snapshots:
|
||||
dependencies:
|
||||
isexe: 2.0.0
|
||||
|
||||
why-is-node-running@2.3.0:
|
||||
dependencies:
|
||||
siginfo: 2.0.0
|
||||
stackback: 0.0.2
|
||||
|
||||
word-wrap@1.2.5: {}
|
||||
|
||||
xml-name-validator@4.0.0: {}
|
||||
@@ -4811,8 +4568,6 @@ snapshots:
|
||||
|
||||
yocto-queue@0.1.0: {}
|
||||
|
||||
zod@4.4.3: {}
|
||||
|
||||
zrender@6.1.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
autoInstallPeers: false
|
||||
|
||||
minimumReleaseAgeExclude:
|
||||
- vite@8.1.3
|
||||
|
||||
@@ -1,207 +1,46 @@
|
||||
import { z } from 'zod'
|
||||
import request from '../request'
|
||||
|
||||
import request, { requestParsed } from '../request'
|
||||
|
||||
const ACCOUNT_EXPORT_CONFIRMATION = 'export_sensitive_accounts'
|
||||
|
||||
const quotaWindowLocalUsageSchema = z.object({
|
||||
requestCount: z.number(),
|
||||
requestCountDisplay: z.string(),
|
||||
inputTokens: z.number(),
|
||||
inputTokensDisplay: z.string(),
|
||||
outputTokens: z.number(),
|
||||
outputTokensDisplay: z.string(),
|
||||
cachedTokens: z.number(),
|
||||
cachedTokensDisplay: z.string(),
|
||||
totalTokens: z.number(),
|
||||
totalTokensDisplay: z.string(),
|
||||
})
|
||||
|
||||
const quotaWindowSchema = z.object({
|
||||
key: z.string(),
|
||||
group: z.enum(['monthly', 'shortTerm', 'other']),
|
||||
windowSeconds: z.number().nullable(),
|
||||
labelDisplay: z.string(),
|
||||
usedPercent: z.number().nullable(),
|
||||
usedPercentDisplay: z.string(),
|
||||
localUsage: quotaWindowLocalUsageSchema.optional(),
|
||||
resetAtDisplay: z.string(),
|
||||
windowUsedDisplay: z.string(),
|
||||
})
|
||||
|
||||
const accountQuotaSchema = z.object({
|
||||
refreshedAtDisplay: z.string(),
|
||||
windows: z.array(quotaWindowSchema),
|
||||
})
|
||||
|
||||
const accountModelUsageSchema = z
|
||||
.object({
|
||||
model: z.string(),
|
||||
requestCount: z.number(),
|
||||
requestCountDisplay: z.string(),
|
||||
successRate: z.number(),
|
||||
successRateDisplay: z.string(),
|
||||
inputTokens: z.number(),
|
||||
inputTokensDisplay: z.string(),
|
||||
outputTokens: z.number(),
|
||||
outputTokensDisplay: z.string(),
|
||||
cachedTokens: z.number(),
|
||||
cachedTokensDisplay: z.string(),
|
||||
totalTokens: z.number(),
|
||||
totalTokensDisplay: z.string(),
|
||||
billingAmountUsd: z.number(),
|
||||
billingAmountUsdDisplay: z.string(),
|
||||
lastUsedAt: z.string().nullable(),
|
||||
lastUsedAtDisplay: z.string(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const accountUsageSchema = z
|
||||
.object({
|
||||
inputTokensDisplay: z.string(),
|
||||
outputTokensDisplay: z.string(),
|
||||
cachedTokensDisplay: z.string(),
|
||||
createdTokensDisplay: z.string(),
|
||||
readTokensDisplay: z.string(),
|
||||
models: z.array(accountModelUsageSchema),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const accountSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
email: z.string().nullable(),
|
||||
accountId: z.string().nullable(),
|
||||
userId: z.string().nullable(),
|
||||
label: z.string().nullable(),
|
||||
planType: z.string().nullable(),
|
||||
hasRefreshToken: z.boolean(),
|
||||
status: z.string(),
|
||||
displayStatus: z.string(),
|
||||
tokenRefreshing: z.boolean(),
|
||||
accessTokenExpiresAt: z.string().nullable(),
|
||||
accessTokenExpiresAtDisplay: z.string().nullable(),
|
||||
addedAt: z.string(),
|
||||
addedAtDisplay: z.string(),
|
||||
updatedAt: z.string(),
|
||||
updatedAtDisplay: z.string(),
|
||||
quota: accountQuotaSchema,
|
||||
usage: accountUsageSchema,
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const accountPageSchema = z.object({
|
||||
items: z.array(accountSchema),
|
||||
page: z.object({
|
||||
page: z.number(),
|
||||
pageSize: z.number(),
|
||||
total: z.number(),
|
||||
totalPages: z.number(),
|
||||
}),
|
||||
summary: z.object({
|
||||
total: z.number(),
|
||||
active: z.number(),
|
||||
quotaExhausted: z.number(),
|
||||
attention: z.number(),
|
||||
}),
|
||||
})
|
||||
|
||||
const _accountQuerySchema = z.object({
|
||||
page: z.number().optional(),
|
||||
pageSize: z.number().optional(),
|
||||
search: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
sortBy: z.string().optional(),
|
||||
sortDirection: z.enum(['asc', 'desc']).optional(),
|
||||
})
|
||||
|
||||
const importResultSchema = z.object({
|
||||
imported: z.number(),
|
||||
skipped: z.number(),
|
||||
sourceFormat: z.string(),
|
||||
})
|
||||
|
||||
const oauthAuthorizeSchema = z.object({
|
||||
sessionId: z.string(),
|
||||
authUrl: z.string(),
|
||||
expiresAt: z.string(),
|
||||
expiresAtDisplay: z.string(),
|
||||
})
|
||||
|
||||
const accountRefreshSchema = z.object({
|
||||
id: z.string(),
|
||||
email: z.string().nullable(),
|
||||
previousStatus: z.string(),
|
||||
result: z.enum(['alive', 'dead', 'skipped']),
|
||||
error: z.string().nullable(),
|
||||
durationMs: z.number(),
|
||||
})
|
||||
|
||||
const accountQuotaRefreshSchema = z
|
||||
.object({
|
||||
quota: z.unknown(),
|
||||
raw: z.unknown(),
|
||||
quotaData: accountQuotaSchema,
|
||||
planType: z.string().nullable(),
|
||||
account: accountSchema,
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const accountModelsSchema = z.object({
|
||||
models: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
type JsonObject = Record<string, unknown>
|
||||
|
||||
export function getAccounts(params?: z.input<typeof _accountQuerySchema>) {
|
||||
return requestParsed({
|
||||
export function getAccounts(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, accountPageSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function importAccounts(data: JsonObject) {
|
||||
return requestParsed({
|
||||
export function importAccounts(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/import',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, importResultSchema)
|
||||
}
|
||||
|
||||
export function exportAccounts(params?: { ids?: string }) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/export',
|
||||
method: 'GET',
|
||||
params: {
|
||||
...params,
|
||||
confirm: ACCOUNT_EXPORT_CONFIRMATION,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function authorizeAccountOAuth(data = {}) {
|
||||
return requestParsed({
|
||||
export function exportAccounts(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/export',
|
||||
method: 'GET',
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function authorizeAccountOAuth(data?: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/oauth/authorize',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, oauthAuthorizeSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function exchangeAccountOAuth(data: JsonObject) {
|
||||
return requestParsed({
|
||||
export function exchangeAccountOAuth(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/oauth/exchange',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, importResultSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteAccounts(data: { ids: string[] }) {
|
||||
export function deleteAccounts(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/delete',
|
||||
method: 'POST',
|
||||
@@ -209,15 +48,15 @@ export function deleteAccounts(data: { ids: string[] }) {
|
||||
})
|
||||
}
|
||||
|
||||
export function refreshAccount(data: { id: string }) {
|
||||
return requestParsed({
|
||||
export function refreshAccount(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/refresh',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, accountRefreshSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function updateAccount(data: { id: string, status?: string, label?: string | null }) {
|
||||
export function updateAccount(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/update',
|
||||
method: 'POST',
|
||||
@@ -225,28 +64,26 @@ export function updateAccount(data: { id: string, status?: string, label?: strin
|
||||
})
|
||||
}
|
||||
|
||||
export function getAccountQuota(params: { id: string }) {
|
||||
return requestParsed({
|
||||
export function getAccountQuota(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/quota',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, accountQuotaRefreshSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getAccountModels(data: { id: string }) {
|
||||
return requestParsed({
|
||||
export function getAccountModels(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/models',
|
||||
method: 'GET',
|
||||
params: {
|
||||
id: data.id,
|
||||
},
|
||||
}, accountModelsSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function refreshAccountModels(data: { id: string }) {
|
||||
return requestParsed({
|
||||
export function refreshAccountModels(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/accounts/models',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, accountModelsSchema)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,85 +1,33 @@
|
||||
import { z } from 'zod'
|
||||
import request from '../request'
|
||||
|
||||
import { requestParsed } from '../request'
|
||||
|
||||
const apiKeySchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
label: z.string().nullable(),
|
||||
prefix: z.string(),
|
||||
key: z.string(),
|
||||
enabled: z.boolean(),
|
||||
createdAt: z.string(),
|
||||
createdAtDisplay: z.string(),
|
||||
lastUsedAt: z.string().nullable(),
|
||||
lastUsedAtDisplay: z.string(),
|
||||
})
|
||||
|
||||
const pageSchema = z.object({
|
||||
page: z.number(),
|
||||
pageSize: z.number(),
|
||||
total: z.number(),
|
||||
totalPages: z.number(),
|
||||
})
|
||||
|
||||
const apiKeyPageSchema = z.object({
|
||||
items: z.array(apiKeySchema),
|
||||
page: pageSchema,
|
||||
})
|
||||
|
||||
const _apiKeyQuerySchema = z.object({
|
||||
page: z.number().optional(),
|
||||
pageSize: z.number().optional(),
|
||||
search: z.string().optional(),
|
||||
sortBy: z.string().optional(),
|
||||
sortDirection: z.enum(['asc', 'desc']).optional(),
|
||||
})
|
||||
|
||||
const _createApiKeySchema = z.object({
|
||||
name: z.string(),
|
||||
label: z.string().optional(),
|
||||
})
|
||||
const _deleteApiKeysSchema = z.object({ ids: z.array(z.string()) })
|
||||
const _updateApiKeySchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
label: z.string().nullable().optional(),
|
||||
status: z.enum(['active', 'disabled']).optional(),
|
||||
})
|
||||
.refine(value => value.label !== undefined || value.status !== undefined)
|
||||
|
||||
const batchDeleteResultSchema = z.object({
|
||||
deleted: z.number(),
|
||||
})
|
||||
|
||||
export function getApiKeys(params: z.input<typeof _apiKeyQuerySchema>) {
|
||||
return requestParsed({
|
||||
export function getApiKeys(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/keys',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, apiKeyPageSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function createApiKey(data: z.input<typeof _createApiKeySchema>) {
|
||||
return requestParsed({
|
||||
export function createApiKey(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/keys',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, apiKeySchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteApiKeys(data: z.input<typeof _deleteApiKeysSchema>) {
|
||||
return requestParsed({
|
||||
export function deleteApiKeys(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/keys/delete',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, batchDeleteResultSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function updateApiKey(data: z.input<typeof _updateApiKeySchema>) {
|
||||
return requestParsed({
|
||||
export function updateApiKey(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/keys/update',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, apiKeySchema)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,42 +1,23 @@
|
||||
import { z } from 'zod'
|
||||
import request from '../request'
|
||||
|
||||
import { requestParsed } from '../request'
|
||||
|
||||
const _loginPayloadSchema = z.object({
|
||||
username: z.string().optional(),
|
||||
password: z.string(),
|
||||
})
|
||||
|
||||
const loginResultSchema = z.object({
|
||||
expiresAt: z.string(),
|
||||
})
|
||||
|
||||
const authStatusSchema = z.object({
|
||||
authenticated: z.boolean(),
|
||||
})
|
||||
|
||||
const logoutResultSchema = z.object({
|
||||
message: z.string(),
|
||||
})
|
||||
|
||||
export function login(data: z.input<typeof _loginPayloadSchema>) {
|
||||
return requestParsed({
|
||||
export function login(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/login',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, loginResultSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function getAuthStatus() {
|
||||
return requestParsed({
|
||||
return request({
|
||||
url: '/api/admin/auth/status',
|
||||
method: 'GET',
|
||||
}, authStatusSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function logout() {
|
||||
return requestParsed({
|
||||
return request({
|
||||
url: '/api/admin/logout',
|
||||
method: 'POST',
|
||||
}, logoutResultSchema)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,235 +1,17 @@
|
||||
import { z } from 'zod'
|
||||
import request from '../request'
|
||||
|
||||
import { requestParsed } from '../request'
|
||||
|
||||
const trendKindSchema = z.enum(['usage', 'latency', 'errors'])
|
||||
|
||||
const trendPointSchema = z
|
||||
.object({
|
||||
time: z.string(),
|
||||
requests: z.string(),
|
||||
requestsValue: z.number(),
|
||||
inputTokens: z.string(),
|
||||
inputTokensValue: z.number(),
|
||||
outputTokens: z.string(),
|
||||
outputTokensValue: z.number(),
|
||||
cachedTokens: z.string(),
|
||||
cachedTokensValue: z.number(),
|
||||
cacheHitRateValue: z.number(),
|
||||
tokensValue: z.number(),
|
||||
errors: z.string(),
|
||||
errorsValue: z.number(),
|
||||
latency: z.string(),
|
||||
latencyValue: z.number().nullable(),
|
||||
maxLatency: z.string(),
|
||||
maxLatencyValue: z.number().nullable(),
|
||||
minLatency: z.string(),
|
||||
minLatencyValue: z.number().nullable(),
|
||||
successRate: z.string(),
|
||||
successRateValue: z.number().nullable(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const dashboardTrendSchema = z.object({
|
||||
kind: trendKindSchema,
|
||||
points: z.array(trendPointSchema),
|
||||
summary: z.array(
|
||||
z.object({
|
||||
label: z.string(),
|
||||
value: z.string(),
|
||||
ratio: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
const healthPointSchema = z.object({
|
||||
time: z.string(),
|
||||
status: z.enum(['future', 'no_data', 'unavailable', 'unstable', 'low_sample', 'stable']),
|
||||
reliabilityDisplay: z.string(),
|
||||
successRequests: z.number(),
|
||||
failedRequests: z.number(),
|
||||
cancelledRequests: z.number(),
|
||||
callerErrorRequests: z.number(),
|
||||
})
|
||||
|
||||
const healthTimelineSchema = z.object({
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
reliabilityDisplay: z.string(),
|
||||
status: healthPointSchema.shape.status,
|
||||
successRequests: z.number(),
|
||||
failedRequests: z.number(),
|
||||
cancelledRequests: z.number(),
|
||||
callerErrorRequests: z.number(),
|
||||
points: z.array(healthPointSchema),
|
||||
})
|
||||
|
||||
const tokenDetailsSchema = z
|
||||
.object({
|
||||
inputTokens: z.number(),
|
||||
outputTokens: z.number(),
|
||||
cachedTokens: z.number(),
|
||||
cacheWriteTokens: z.number(),
|
||||
reasoningTokens: z.number(),
|
||||
totalTokens: z.number(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const billingSchema = z
|
||||
.object({
|
||||
totalAmount: z.number(),
|
||||
totalAmountDisplay: z.string(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const dashboardUsageRecordSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
route: z.string().nullable(),
|
||||
model: z.string(),
|
||||
statusCode: z.number(),
|
||||
transport: z.string().nullable(),
|
||||
createdAtDisplay: z.string(),
|
||||
accountEmail: z.string().nullable(),
|
||||
requestedModel: z.string().nullable(),
|
||||
upstreamModel: z.string().nullable(),
|
||||
clientIp: z.string().nullable(),
|
||||
userAgent: z.string().nullable(),
|
||||
reasoningEffort: z.string().nullable(),
|
||||
reasoningPreset: z.string().nullable(),
|
||||
compact: z.boolean(),
|
||||
requestKind: z.string().nullable(),
|
||||
subagentKind: z.string().nullable(),
|
||||
tokenDetails: tokenDetailsSchema,
|
||||
billing: billingSchema.nullable(),
|
||||
firstTokenLatencyMs: z.number().nullable(),
|
||||
latencyMs: z.number().nullable(),
|
||||
latencyDetails: z.object({
|
||||
firstReasoningMs: z.number().nullable(),
|
||||
firstTextMs: z.number().nullable(),
|
||||
transportDecisionWaitMs: z.number().nullable(),
|
||||
wsConnectMs: z.number().nullable(),
|
||||
upstreamHeadersMs: z.number().nullable(),
|
||||
firstEventMs: z.number().nullable(),
|
||||
openaiProcessingMs: z.number().nullable(),
|
||||
}),
|
||||
firstTokenLatencyMsDisplay: z.string(),
|
||||
latencyMsDisplay: z.string(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const wireProfileSchema = z
|
||||
.object({
|
||||
originator: z.string(),
|
||||
codexVersion: z.string(),
|
||||
desktopVersion: z.string(),
|
||||
desktopBuild: z.string(),
|
||||
target: z.object({
|
||||
osType: z.string(),
|
||||
osVersion: z.string(),
|
||||
arch: z.string(),
|
||||
terminal: z.string(),
|
||||
}),
|
||||
userAgent: z.string(),
|
||||
verifiedAt: z.string(),
|
||||
release: z
|
||||
.object({
|
||||
status: z.string(),
|
||||
checkedAt: z.string().optional(),
|
||||
latestVersion: z.string().optional(),
|
||||
latestBuild: z.string().optional(),
|
||||
publishedAt: z.string().optional(),
|
||||
minimumSystemVersion: z.string().optional(),
|
||||
hardwareRequirements: z.string().optional(),
|
||||
downloadUrl: z.string().optional(),
|
||||
downloadSize: z.number().optional(),
|
||||
signaturePresent: z.boolean().optional(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const dashboardSummarySchema = z.object({
|
||||
cards: z.object({
|
||||
accounts: z.object({
|
||||
total: z.string(),
|
||||
totalValue: z.number(),
|
||||
enabled: z.string(),
|
||||
enabledValue: z.number(),
|
||||
abnormal: z.string(),
|
||||
abnormalValue: z.number(),
|
||||
}),
|
||||
traffic: z.object({
|
||||
todayRequests: z.string(),
|
||||
todayRequestsValue: z.number(),
|
||||
yesterdayRequestsValue: z.number(),
|
||||
totalRequests: z.string(),
|
||||
}),
|
||||
tokens: z.object({
|
||||
todayTokens: z.string(),
|
||||
todayTokensValue: z.number(),
|
||||
yesterdayTokensValue: z.number(),
|
||||
totalTokens: z.string(),
|
||||
totalBillingAmountUsd: z.string(),
|
||||
}),
|
||||
cache: z.object({
|
||||
todayHitRate: z.string(),
|
||||
todayHitRateValue: z.number().nullable(),
|
||||
yesterdayHitRateValue: z.number().nullable(),
|
||||
totalHitRate: z.string(),
|
||||
totalCachedTokens: z.string(),
|
||||
averageFirstTokenLatencyMs: z.string(),
|
||||
}),
|
||||
}),
|
||||
trend: dashboardTrendSchema,
|
||||
healthTimeline: healthTimelineSchema,
|
||||
accountUsage: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
email: z.string(),
|
||||
planType: z.string().nullable(),
|
||||
tokens: z.string(),
|
||||
quotaUsedPercent: z.number().nullable(),
|
||||
lastUsed: z.string(),
|
||||
}),
|
||||
),
|
||||
wireProfile: wireProfileSchema,
|
||||
usageRecords: z.array(dashboardUsageRecordSchema),
|
||||
poolSummary: z.object({
|
||||
total: z.number(),
|
||||
active: z.number(),
|
||||
expired: z.number(),
|
||||
quotaExhausted: z.number(),
|
||||
refreshing: z.number(),
|
||||
disabled: z.number(),
|
||||
banned: z.number(),
|
||||
}),
|
||||
capacityInfo: z.object({
|
||||
maxConcurrentPerAccount: z.number(),
|
||||
totalSlots: z.number(),
|
||||
usedSlots: z.number(),
|
||||
availableSlots: z.number(),
|
||||
}),
|
||||
rotationStrategy: z.string().nullable(),
|
||||
})
|
||||
|
||||
const _dashboardQuerySchema = z.object({
|
||||
kind: trendKindSchema.optional(),
|
||||
})
|
||||
|
||||
export function getDashboardSummary(params?: z.input<typeof _dashboardQuerySchema>) {
|
||||
return requestParsed({
|
||||
export function getDashboardSummary(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/dashboard/summary',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, dashboardSummarySchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getDashboardTrend(params: z.input<typeof _dashboardQuerySchema>) {
|
||||
return requestParsed({
|
||||
export function getDashboardTrend(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/dashboard/trend',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, dashboardTrendSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,67 +1,37 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
import { requestParsed } from '../request'
|
||||
|
||||
const rotationStrategySchema = z.enum([
|
||||
'smart',
|
||||
'quota_reset_priority',
|
||||
'round_robin',
|
||||
'sticky',
|
||||
])
|
||||
|
||||
const settingsSchema = z.object({
|
||||
modelAliases: z.record(z.string(), z.string()),
|
||||
refreshMarginSeconds: z.number(),
|
||||
refreshConcurrency: z.number(),
|
||||
maxConcurrentPerAccount: z.number(),
|
||||
requestIntervalMs: z.number(),
|
||||
rotationStrategy: rotationStrategySchema,
|
||||
})
|
||||
|
||||
const adminApiKeyStatusSchema = z.object({
|
||||
exists: z.boolean(),
|
||||
})
|
||||
|
||||
const generatedAdminApiKeySchema = z.object({
|
||||
key: z.string(),
|
||||
})
|
||||
|
||||
const messageSchema = z.object({
|
||||
message: z.string(),
|
||||
})
|
||||
import request from '../request'
|
||||
|
||||
export function getSettings() {
|
||||
return requestParsed({
|
||||
return request({
|
||||
url: '/api/admin/settings',
|
||||
method: 'GET',
|
||||
}, settingsSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function updateSettings(data: z.input<typeof settingsSchema>) {
|
||||
return requestParsed({
|
||||
export function updateSettings(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/settings',
|
||||
method: 'POST',
|
||||
data,
|
||||
}, settingsSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function getAdminApiKeyStatus() {
|
||||
return requestParsed({
|
||||
return request({
|
||||
url: '/api/admin/settings/admin-api-key',
|
||||
method: 'GET',
|
||||
}, adminApiKeyStatusSchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function regenerateAdminApiKey() {
|
||||
return requestParsed({
|
||||
return request({
|
||||
url: '/api/admin/settings/admin-api-key/regenerate',
|
||||
method: 'POST',
|
||||
}, generatedAdminApiKeySchema)
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteAdminApiKey() {
|
||||
return requestParsed({
|
||||
return request({
|
||||
url: '/api/admin/settings/admin-api-key',
|
||||
method: 'DELETE',
|
||||
}, messageSchema)
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,76 +1,32 @@
|
||||
import { z } from 'zod'
|
||||
import request from '../request'
|
||||
|
||||
import { requestParsed } from '../request'
|
||||
|
||||
const versionSchema = z.object({
|
||||
version: z.string(),
|
||||
gitSha: z.string(),
|
||||
buildTime: z.string(),
|
||||
deploymentMode: z.string(),
|
||||
deploymentModeLabel: z.string(),
|
||||
updateChannel: z.string(),
|
||||
latestVersion: z.string(),
|
||||
hasUpdate: z.boolean(),
|
||||
updateCached: z.boolean(),
|
||||
updateWarning: z.string().nullable(),
|
||||
})
|
||||
|
||||
const updateDetailSchema = z.object({
|
||||
currentVersion: z.string(),
|
||||
latestVersion: z.string(),
|
||||
hasUpdate: z.boolean(),
|
||||
deploymentMode: z.string(),
|
||||
deploymentModeLabel: z.string(),
|
||||
buildType: z.string(),
|
||||
buildTypeLabel: z.string(),
|
||||
releaseUrl: z.string().nullable(),
|
||||
notes: z.string().nullable(),
|
||||
cached: z.boolean(),
|
||||
updateSupported: z.boolean(),
|
||||
unsupportedReason: z.string().nullable(),
|
||||
warning: z.string().nullable(),
|
||||
})
|
||||
|
||||
const updateStartedSchema = z.object({
|
||||
operationId: z.string(),
|
||||
deploymentMode: z.string(),
|
||||
message: z.string(),
|
||||
needRestart: z.boolean(),
|
||||
targetVersion: z.string(),
|
||||
})
|
||||
|
||||
const restartResultSchema = z.object({
|
||||
message: z.string(),
|
||||
operationId: z.string(),
|
||||
})
|
||||
|
||||
export function getSystemVersion(options: { timeoutMs?: number } = {}) {
|
||||
return requestParsed({
|
||||
export function getSystemVersion(timeout = 0) {
|
||||
return request({
|
||||
url: '/api/admin/system/version',
|
||||
method: 'GET',
|
||||
...(options.timeoutMs ? { timeout: options.timeoutMs } : {}),
|
||||
}, versionSchema)
|
||||
...(timeout ? { timeout } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export function getSystemUpdateDetail(refresh = false) {
|
||||
return requestParsed({
|
||||
export function getSystemUpdateDetail(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/system/update-detail',
|
||||
method: 'GET',
|
||||
params: { refresh },
|
||||
}, updateDetailSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function performSystemUpdate(targetVersion: string) {
|
||||
return requestParsed({
|
||||
export function performSystemUpdate(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/system/update',
|
||||
method: 'POST',
|
||||
data: { targetVersion },
|
||||
}, updateStartedSchema)
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
export function restartSystem() {
|
||||
return requestParsed({
|
||||
return request({
|
||||
url: '/api/admin/system/restart',
|
||||
method: 'POST',
|
||||
}, restartResultSchema)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,308 +1,49 @@
|
||||
import { z } from 'zod'
|
||||
import request from '../request'
|
||||
|
||||
import { requestParsed } from '../request'
|
||||
|
||||
const pageSchema = z.object({
|
||||
page: z.number(),
|
||||
pageSize: z.number(),
|
||||
total: z.number(),
|
||||
totalPages: z.number(),
|
||||
})
|
||||
|
||||
const usageQuerySchema = z.object({
|
||||
page: z.number().optional(),
|
||||
pageSize: z.number().optional(),
|
||||
kind: z.string().optional(),
|
||||
clientApiKeyId: z.string().optional(),
|
||||
provider: z.string().optional(),
|
||||
requestId: z.string().optional(),
|
||||
accountId: z.string().optional(),
|
||||
route: z.string().optional(),
|
||||
model: z.string().optional(),
|
||||
statusCode: z.number().optional(),
|
||||
transport: z.string().optional(),
|
||||
attemptIndex: z.number().optional(),
|
||||
responseId: z.string().optional(),
|
||||
upstreamRequestId: z.string().optional(),
|
||||
search: z.string().optional(),
|
||||
startTime: z.string().optional(),
|
||||
endTime: z.string().optional(),
|
||||
})
|
||||
|
||||
const tokenDetailsSchema = z.object({
|
||||
inputTokens: z.number(),
|
||||
outputTokens: z.number(),
|
||||
cachedTokens: z.number(),
|
||||
cacheWriteTokens: z.number(),
|
||||
reasoningTokens: z.number(),
|
||||
totalTokens: z.number(),
|
||||
inputTokensDisplay: z.string(),
|
||||
outputTokensDisplay: z.string(),
|
||||
cachedTokensDisplay: z.string(),
|
||||
cacheWriteTokensDisplay: z.string(),
|
||||
reasoningTokensDisplay: z.string(),
|
||||
totalTokensDisplay: z.string(),
|
||||
})
|
||||
|
||||
const billingSchema = z.object({
|
||||
inputAmount: z.number(),
|
||||
outputAmount: z.number(),
|
||||
cacheReadAmount: z.number(),
|
||||
cacheWriteAmount: z.number(),
|
||||
standardAmount: z.number(),
|
||||
totalAmount: z.number(),
|
||||
inputPricePerMtoken: z.number(),
|
||||
outputPricePerMtoken: z.number(),
|
||||
cacheReadPricePerMtoken: z.number(),
|
||||
cacheWritePricePerMtoken: z.number(),
|
||||
serviceTier: z.string().nullable(),
|
||||
serviceTierDisplay: z.string(),
|
||||
multiplier: z.number(),
|
||||
inputAmountDisplay: z.string(),
|
||||
outputAmountDisplay: z.string(),
|
||||
cacheReadAmountDisplay: z.string(),
|
||||
cacheWriteAmountDisplay: z.string(),
|
||||
standardAmountDisplay: z.string(),
|
||||
totalAmountDisplay: z.string(),
|
||||
inputPriceDisplay: z.string(),
|
||||
outputPriceDisplay: z.string(),
|
||||
cacheReadPriceDisplay: z.string(),
|
||||
cacheWritePriceDisplay: z.string(),
|
||||
multiplierDisplay: z.string(),
|
||||
})
|
||||
|
||||
const usageRecordSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
requestId: z.string().nullable(),
|
||||
clientApiKeyId: z.string().nullable(),
|
||||
kind: z.string(),
|
||||
provider: z.string(),
|
||||
accountId: z.string(),
|
||||
route: z.string().nullable(),
|
||||
model: z.string(),
|
||||
requestedModel: z.string().nullable(),
|
||||
upstreamModel: z.string().nullable(),
|
||||
serviceTier: z.string().nullable(),
|
||||
statusCode: z.number(),
|
||||
transport: z.string().nullable(),
|
||||
attemptIndex: z.number().nullable(),
|
||||
responseId: z.string().nullable(),
|
||||
upstreamRequestId: z.string().nullable(),
|
||||
latencyMs: z.number().nullable(),
|
||||
firstTokenMs: z.number().nullable(),
|
||||
inputTokens: z.number().nullable(),
|
||||
outputTokens: z.number().nullable(),
|
||||
cachedTokens: z.number().nullable(),
|
||||
cacheWriteTokens: z.number().nullable(),
|
||||
reasoningTokens: z.number().nullable(),
|
||||
message: z.string(),
|
||||
metadata: z.unknown(),
|
||||
createdAt: z.string(),
|
||||
createdAtDisplay: z.string(),
|
||||
accountEmail: z.string().nullable(),
|
||||
clientIp: z.string().nullable(),
|
||||
userAgent: z.string().nullable(),
|
||||
reasoningEffort: z.string().nullable(),
|
||||
reasoningPreset: z.string().nullable(),
|
||||
compact: z.boolean(),
|
||||
requestKind: z.string().nullable(),
|
||||
subagentKind: z.string().nullable(),
|
||||
tokenDetails: tokenDetailsSchema,
|
||||
billing: billingSchema.nullable(),
|
||||
firstTokenLatencyMs: z.number().nullable(),
|
||||
firstTokenLatencyMsDisplay: z.string(),
|
||||
latencyMsDisplay: z.string(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const usagePageSchema = z.object({
|
||||
items: z.array(usageRecordSchema),
|
||||
page: pageSchema,
|
||||
})
|
||||
|
||||
const usageSummarySchema = z.object({
|
||||
totalRequests: z.string(),
|
||||
inputTokens: z.string(),
|
||||
outputTokens: z.string(),
|
||||
cachedTokens: z.string(),
|
||||
cacheWriteTokens: z.string(),
|
||||
totalTokens: z.string(),
|
||||
averageLatencyMs: z.string(),
|
||||
})
|
||||
|
||||
const healthPointSchema = z.object({
|
||||
bucket: z.string(),
|
||||
label: z.string(),
|
||||
successRequests: z.number(),
|
||||
failedRequests: z.number(),
|
||||
cancelledRequests: z.number(),
|
||||
callerErrorRequests: z.number(),
|
||||
errorRate: z.number(),
|
||||
})
|
||||
|
||||
const performancePointSchema = z.object({
|
||||
bucket: z.string(),
|
||||
label: z.string(),
|
||||
latencyP50Ms: z.number().nullable(),
|
||||
latencyP95Ms: z.number().nullable(),
|
||||
latencyP99Ms: z.number().nullable(),
|
||||
firstTokenP50Ms: z.number().nullable(),
|
||||
firstTokenP95Ms: z.number().nullable(),
|
||||
firstTokenP99Ms: z.number().nullable(),
|
||||
})
|
||||
|
||||
const costPointSchema = z.object({
|
||||
bucket: z.string(),
|
||||
label: z.string(),
|
||||
inputTokens: z.number(),
|
||||
outputTokens: z.number(),
|
||||
cachedTokens: z.number(),
|
||||
totalTokens: z.number(),
|
||||
estimatedCost: z.number(),
|
||||
standardCost: z.number(),
|
||||
cachedTokenRate: z.number(),
|
||||
cacheHitRequestRate: z.number(),
|
||||
})
|
||||
|
||||
const usageOverviewSchema = z.object({
|
||||
granularity: z.string(),
|
||||
health: z.object({
|
||||
totalRequests: z.number(),
|
||||
successRequests: z.number(),
|
||||
failedRequests: z.number(),
|
||||
cancelledRequests: z.number(),
|
||||
callerErrorRequests: z.number(),
|
||||
successRate: z.number(),
|
||||
requestChangeRate: z.number().nullable(),
|
||||
successRateChange: z.number().nullable(),
|
||||
points: z.array(healthPointSchema),
|
||||
}),
|
||||
performance: z.object({
|
||||
latencyP50Ms: z.number().nullable(),
|
||||
latencyP95Ms: z.number().nullable(),
|
||||
latencyP99Ms: z.number().nullable(),
|
||||
firstTokenP50Ms: z.number().nullable(),
|
||||
firstTokenP95Ms: z.number().nullable(),
|
||||
firstTokenP99Ms: z.number().nullable(),
|
||||
latencyCoverage: z.number(),
|
||||
firstTokenCoverage: z.number(),
|
||||
points: z.array(performancePointSchema),
|
||||
}),
|
||||
cost: z.object({
|
||||
estimatedCost: z.number(),
|
||||
standardCost: z.number(),
|
||||
costPerRequest: z.number(),
|
||||
tokensPerRequest: z.number(),
|
||||
cachedTokenRate: z.number(),
|
||||
cacheHitRequestRate: z.number(),
|
||||
inputTokens: z.number(),
|
||||
outputTokens: z.number(),
|
||||
cachedTokens: z.number(),
|
||||
totalTokens: z.number(),
|
||||
points: z.array(costPointSchema),
|
||||
}),
|
||||
})
|
||||
|
||||
const diagnosticsSchema = z.object({
|
||||
dimension: z.string(),
|
||||
items: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
requestCount: z.number(),
|
||||
successCount: z.number(),
|
||||
errorCount: z.number(),
|
||||
errorRate: z.number(),
|
||||
requestShare: z.number(),
|
||||
latencyP95Ms: z.number().nullable(),
|
||||
estimatedCost: z.number(),
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
const opsErrorSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
requestId: z.string().nullable(),
|
||||
clientApiKeyId: z.string().nullable(),
|
||||
kind: z.string(),
|
||||
provider: z.string().nullable(),
|
||||
accountId: z.string().nullable(),
|
||||
route: z.string().nullable(),
|
||||
model: z.string().nullable(),
|
||||
statusCode: z.number().nullable(),
|
||||
clientStatusCode: z.number().nullable(),
|
||||
upstreamStatusCode: z.number().nullable(),
|
||||
transport: z.string().nullable(),
|
||||
attemptIndex: z.number().nullable(),
|
||||
failureClass: z.string().nullable(),
|
||||
responseId: z.string().nullable(),
|
||||
upstreamRequestId: z.string().nullable(),
|
||||
latencyMs: z.number().nullable(),
|
||||
message: z.string(),
|
||||
metadata: z.unknown(),
|
||||
createdAt: z.string(),
|
||||
createdAtDisplay: z.string(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const _opsQuerySchema = usageQuerySchema.extend({
|
||||
clientStatusCode: z.number().optional(),
|
||||
upstreamStatusCode: z.number().optional(),
|
||||
failureClass: z.string().optional(),
|
||||
})
|
||||
|
||||
const _rangeSchema = z.object({
|
||||
startTime: z.string().optional(),
|
||||
endTime: z.string().optional(),
|
||||
})
|
||||
|
||||
export function getUsageRecords(params?: z.input<typeof usageQuerySchema>) {
|
||||
return requestParsed({
|
||||
export function getUsageRecords(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/usage/records',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, usagePageSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getOpsErrors(params?: z.input<typeof _opsQuerySchema>) {
|
||||
return requestParsed({
|
||||
export function getOpsErrors(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/ops/errors',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, z.object({ items: z.array(opsErrorSchema), page: pageSchema }))
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getUsageRecordDetail(params: { id: string }) {
|
||||
return requestParsed({
|
||||
export function getUsageRecordDetail(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/usage/records/detail',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, usageRecordSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getUsageRecordSummary(params?: z.input<typeof _rangeSchema>) {
|
||||
return requestParsed({
|
||||
export function getUsageRecordSummary(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/usage/records/summary',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, usageSummarySchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getUsageRecordInsightsOverview(params?: z.input<typeof _rangeSchema>) {
|
||||
return requestParsed({
|
||||
export function getUsageRecordInsightsOverview(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/usage/records/insights/overview',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, usageOverviewSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
export function getUsageRecordInsightsDiagnostics(
|
||||
params: z.input<typeof _rangeSchema> & { dimension: string },
|
||||
) {
|
||||
return requestParsed({
|
||||
export function getUsageRecordInsightsDiagnostics(data: object) {
|
||||
return request({
|
||||
url: '/api/admin/usage/records/insights/diagnostics',
|
||||
method: 'GET',
|
||||
params,
|
||||
}, diagnosticsSchema)
|
||||
params: data,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,25 +4,10 @@ import type {
|
||||
AxiosRequestConfig,
|
||||
AxiosResponse,
|
||||
} from 'axios'
|
||||
import type { ZodType } from 'zod'
|
||||
import axios from 'axios'
|
||||
|
||||
import { API_BASE_URL, API_TIMEOUT_MS } from './constants'
|
||||
|
||||
interface ApiEnvelope<T = unknown> {
|
||||
code: number
|
||||
message: string
|
||||
data: T
|
||||
}
|
||||
|
||||
interface ApiErrorBody {
|
||||
code?: number
|
||||
message?: string
|
||||
data?: unknown
|
||||
}
|
||||
|
||||
type UnauthorizedHandler = () => void | Promise<void>
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
@@ -42,9 +27,9 @@ const http: AxiosInstance = axios.create({
|
||||
})
|
||||
|
||||
let unauthorizedHandled = false
|
||||
let unauthorizedHandler: UnauthorizedHandler | undefined
|
||||
let unauthorizedHandler: (() => void | Promise<void>) | undefined
|
||||
|
||||
export function setUnauthorizedHandler(handler: UnauthorizedHandler) {
|
||||
export function setUnauthorizedHandler(handler: () => void | Promise<void>) {
|
||||
unauthorizedHandler = handler
|
||||
}
|
||||
|
||||
@@ -69,7 +54,7 @@ http.interceptors.response.use(
|
||||
(response: AxiosResponse) => {
|
||||
return response
|
||||
},
|
||||
(error: AxiosError<ApiErrorBody>) => {
|
||||
(error: AxiosError<any>) => {
|
||||
const { response } = error
|
||||
|
||||
const status = response?.status || 0
|
||||
@@ -85,7 +70,7 @@ http.interceptors.response.use(
|
||||
},
|
||||
)
|
||||
|
||||
function isApiEnvelope(value: unknown): value is ApiEnvelope {
|
||||
function isApiEnvelope(value: any) {
|
||||
return (
|
||||
typeof value === 'object'
|
||||
&& value !== null
|
||||
@@ -96,7 +81,7 @@ function isApiEnvelope(value: unknown): value is ApiEnvelope {
|
||||
}
|
||||
|
||||
export default async function request(config: AxiosRequestConfig) {
|
||||
const response = await http.request<unknown, AxiosResponse<unknown>>({
|
||||
const response = await http.request({
|
||||
...config,
|
||||
})
|
||||
|
||||
@@ -106,10 +91,3 @@ export default async function request(config: AxiosRequestConfig) {
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
export async function requestParsed<const Schema extends ZodType>(
|
||||
config: AxiosRequestConfig,
|
||||
schema: Schema,
|
||||
) {
|
||||
return schema.parse(await request(config))
|
||||
}
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
import { API_BASE_URL } from '../constants'
|
||||
|
||||
const requestPayloadSchema = z
|
||||
.object({
|
||||
input: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
content: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
type: z.string().optional(),
|
||||
text: z.string().optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const accountConnectionEventSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('test_start'), model: z.string().optional() }),
|
||||
z.object({ type: z.literal('request'), payload: requestPayloadSchema.optional() }),
|
||||
z.object({ type: z.literal('status'), text: z.string().optional() }),
|
||||
z.object({ type: z.literal('content'), text: z.string().optional() }),
|
||||
z.object({
|
||||
type: z.literal('test_complete'),
|
||||
success: z.boolean().optional(),
|
||||
error: z.string().optional(),
|
||||
accountStatus: z.string().optional(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal('error'),
|
||||
error: z.string().optional(),
|
||||
accountStatus: z.string().optional(),
|
||||
}),
|
||||
])
|
||||
|
||||
export type AccountConnectionEvent = z.infer<typeof accountConnectionEventSchema>
|
||||
|
||||
export function openAccountConnectionStream(options: {
|
||||
accountId: string
|
||||
modelId: string
|
||||
onEvent: (event: AccountConnectionEvent) => void
|
||||
onError: () => void
|
||||
}) {
|
||||
const params = new URLSearchParams({
|
||||
id: options.accountId,
|
||||
modelId: options.modelId,
|
||||
})
|
||||
const source = new EventSource(`${API_BASE_URL}/api/admin/accounts/test?${params}`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
source.onmessage = (event) => {
|
||||
try {
|
||||
options.onEvent(accountConnectionEventSchema.parse(JSON.parse(event.data)))
|
||||
}
|
||||
catch {
|
||||
options.onError()
|
||||
}
|
||||
}
|
||||
source.onerror = options.onError
|
||||
return source
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
import { API_BASE_URL } from '../constants'
|
||||
|
||||
const systemUpdateEventSchema = z.object({
|
||||
id: z.string(),
|
||||
operationId: z.string().nullable().optional(),
|
||||
level: z.enum(['info', 'success', 'warning', 'error']),
|
||||
step: z.string().nullable().optional(),
|
||||
message: z.string(),
|
||||
terminal: z.boolean().optional(),
|
||||
at: z.string(),
|
||||
})
|
||||
|
||||
export type SystemUpdateEvent = z.infer<typeof systemUpdateEventSchema>
|
||||
|
||||
export function openSystemUpdateStream(options: {
|
||||
onOpen: () => void
|
||||
onEvent: (event: SystemUpdateEvent) => void
|
||||
onError: (closed: boolean) => void
|
||||
onParseError: () => void
|
||||
}) {
|
||||
if (typeof EventSource === 'undefined')
|
||||
return null
|
||||
|
||||
const source = new EventSource(`${API_BASE_URL}/api/admin/system/update-events`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
source.onopen = options.onOpen
|
||||
source.addEventListener('update', (event) => {
|
||||
try {
|
||||
options.onEvent(systemUpdateEventSchema.parse(JSON.parse((event as MessageEvent<string>).data)))
|
||||
}
|
||||
catch {
|
||||
options.onParseError()
|
||||
}
|
||||
})
|
||||
source.onerror = () => {
|
||||
options.onError(source.readyState === EventSource.CLOSED)
|
||||
}
|
||||
return source
|
||||
}
|
||||
@@ -23,9 +23,12 @@ withDefaults(
|
||||
>
|
||||
<div class="flex min-w-0 items-center gap-1.5">
|
||||
<slot name="label">
|
||||
<label class="min-w-0 text-[13px] leading-none font-medium text-(--cp-text-secondary)">
|
||||
<span
|
||||
v-if="label"
|
||||
class="min-w-0 text-[13px] leading-none font-medium text-(--cp-text-secondary)"
|
||||
>
|
||||
{{ label }}
|
||||
</label>
|
||||
</span>
|
||||
</slot>
|
||||
<span v-if="required" class="text-[13px] leading-none font-bold text-(--cp-danger)">
|
||||
*
|
||||
|
||||
@@ -8,6 +8,8 @@ const props = withDefaults(
|
||||
disabled?: boolean
|
||||
error?: string
|
||||
autocomplete?: string
|
||||
name?: string
|
||||
ariaLabel?: string
|
||||
}>(),
|
||||
{
|
||||
placeholder: '',
|
||||
@@ -15,6 +17,8 @@ const props = withDefaults(
|
||||
disabled: false,
|
||||
error: undefined,
|
||||
autocomplete: undefined,
|
||||
name: undefined,
|
||||
ariaLabel: undefined,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -54,7 +58,7 @@ const inputClasses = computed(() => [
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<label class="grid box-content gap-2 overflow-visible p-0.75">
|
||||
<div class="grid box-content gap-2 overflow-visible p-0.75">
|
||||
<span class="base-input__control" :class="containerClasses">
|
||||
<span v-if="$slots.prefix" :class="iconClasses">
|
||||
<slot name="prefix" />
|
||||
@@ -63,10 +67,12 @@ const inputClasses = computed(() => [
|
||||
v-model="model"
|
||||
class="base-input__field"
|
||||
:class="inputClasses"
|
||||
:name="name"
|
||||
:placeholder="placeholder"
|
||||
:type="type"
|
||||
:disabled="disabled"
|
||||
:autocomplete="autocomplete"
|
||||
:aria-label="ariaLabel"
|
||||
:aria-invalid="error ? 'true' : undefined"
|
||||
>
|
||||
<span v-if="$slots.suffix" :class="iconClasses">
|
||||
@@ -76,7 +82,7 @@ const inputClasses = computed(() => [
|
||||
<span v-if="error" class="text-xs font-[650] leading-[1.15] text-(--cp-danger-text)">{{
|
||||
error
|
||||
}}</span>
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { AlertCircle, AlertTriangle, CheckCircle2, Info, X } from '@lucide/vue'
|
||||
import { computed, nextTick, onBeforeUnmount, useTemplateRef, watch } from 'vue'
|
||||
|
||||
import { lockBodyScroll, unlockBodyScroll } from '@/utils/bodyScrollLock'
|
||||
import { lockBodyScroll, unlockBodyScroll } from '@/utils/body-scroll-lock'
|
||||
import BaseButton from './BaseButton.vue'
|
||||
import BaseScrollbar from './BaseScrollbar.vue'
|
||||
|
||||
@@ -183,7 +183,13 @@ onBeforeUnmount(() => {
|
||||
role="presentation"
|
||||
@keydown="handleKeydown"
|
||||
>
|
||||
<div class="absolute inset-0 bg-(--cp-overlay-scrim)" @click="closeModal" />
|
||||
<button
|
||||
type="button"
|
||||
tabindex="-1"
|
||||
aria-label="关闭弹窗"
|
||||
class="absolute inset-0 cursor-default border-0 bg-(--cp-overlay-scrim) p-0"
|
||||
@click="closeModal"
|
||||
/>
|
||||
<section
|
||||
ref="panel"
|
||||
class="cp-modal-panel [--cp-input-current-bg:var(--cp-input-soft-bg)] [--cp-input-current-bg-hover:var(--cp-input-soft-bg-hover)] relative grid max-h-[calc(100dvh-1.5rem)] min-w-0 grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden rounded-(--cp-card-radius) bg-(--cp-bg-surface) shadow-(--cp-shadow-popover) sm:max-h-[calc(100dvh-3rem)]"
|
||||
|
||||
@@ -311,12 +311,6 @@ function handleHoverLeave() {
|
||||
hoverCloseTimer.value = window.setTimeout(closePopover, 90)
|
||||
}
|
||||
|
||||
function handleTriggerKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') {
|
||||
closePopover()
|
||||
}
|
||||
}
|
||||
|
||||
whenever(open, async () => {
|
||||
await nextTick()
|
||||
updatePopoverPosition()
|
||||
@@ -332,6 +326,14 @@ watch(
|
||||
)
|
||||
|
||||
onClickOutside(rootRef, closePopover, { ignore: [popoverRef] })
|
||||
useEventListener(triggerRef, 'click', (event) => {
|
||||
event.stopPropagation()
|
||||
togglePopover()
|
||||
})
|
||||
useEventListener(triggerRef, ['mouseenter', 'focusin'], handleHoverEnter)
|
||||
useEventListener(triggerRef, ['mouseleave', 'focusout'], handleHoverLeave)
|
||||
useEventListener(popoverRef, ['mouseenter', 'focusin'], handleHoverEnter)
|
||||
useEventListener(popoverRef, ['mouseleave', 'focusout'], handleHoverLeave)
|
||||
useEventListener(viewportTarget, 'keydown', (event) => {
|
||||
if (event instanceof KeyboardEvent && event.key === 'Escape') {
|
||||
closePopover()
|
||||
@@ -348,10 +350,6 @@ onBeforeUnmount(clearHoverCloseTimer)
|
||||
ref="triggerRef"
|
||||
class="inline-flex"
|
||||
:class="props.triggerClass"
|
||||
@click.stop="togglePopover"
|
||||
@keydown="handleTriggerKeydown"
|
||||
@mouseenter="handleHoverEnter"
|
||||
@mouseleave="handleHoverLeave"
|
||||
>
|
||||
<slot name="trigger" :open="open" :close="closePopover" :toggle="togglePopover" />
|
||||
</div>
|
||||
@@ -370,8 +368,6 @@ onBeforeUnmount(clearHoverCloseTimer)
|
||||
ref="popoverRef"
|
||||
:class="popoverClasses"
|
||||
:style="[sizeStyle, popoverStyle]"
|
||||
@mouseenter="handleHoverEnter"
|
||||
@mouseleave="handleHoverLeave"
|
||||
>
|
||||
<span
|
||||
class="pointer-events-none absolute size-2 rotate-45 bg-inherit"
|
||||
|
||||
@@ -26,8 +26,11 @@ const emit = defineEmits<{
|
||||
scroll: [payload: { scrollTop: number, scrollLeft: number }]
|
||||
}>()
|
||||
|
||||
const rootRef = useTemplateRef<HTMLDivElement>('root')
|
||||
const wrapRef = useTemplateRef<HTMLDivElement>('wrap')
|
||||
const viewRef = useTemplateRef<HTMLElement>('view')
|
||||
const verticalTrackRef = useTemplateRef<HTMLDivElement>('verticalTrack')
|
||||
const horizontalTrackRef = useTemplateRef<HTMLDivElement>('horizontalTrack')
|
||||
const thumbHeight = shallowRef(0)
|
||||
const thumbTop = shallowRef(0)
|
||||
const horizontalThumbWidth = shallowRef(0)
|
||||
@@ -67,7 +70,7 @@ const rootClasses = computed(() => [
|
||||
props.maxHeight || props.height ? undefined : 'h-full',
|
||||
])
|
||||
const wrapClasses = computed(() => [
|
||||
'base-scrollbar-wrap min-h-0 max-h-[inherit] overflow-auto',
|
||||
'base-scrollbar-wrap min-h-0 max-h-[inherit] overflow-auto outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-(--cp-info-border)',
|
||||
props.maxHeight ? undefined : 'h-full',
|
||||
])
|
||||
const verticalTrackClass = computed(() =>
|
||||
@@ -372,6 +375,14 @@ useEventListener(document, 'pointermove', handleThumbPointerMove)
|
||||
useEventListener(document, 'pointerup', handleThumbPointerUp)
|
||||
useEventListener(document, 'pointermove', handleHorizontalThumbPointerMove)
|
||||
useEventListener(document, 'pointerup', handleHorizontalThumbPointerUp)
|
||||
useEventListener(rootRef, ['mouseenter', 'mousemove'], activateScrollbar)
|
||||
useEventListener(rootRef, 'mouseleave', hideScrollbar)
|
||||
useEventListener(verticalTrackRef, 'mouseenter', () => handleTrackMouseEnter('vertical'))
|
||||
useEventListener(verticalTrackRef, 'mouseleave', () => handleTrackMouseLeave('vertical'))
|
||||
useEventListener(verticalTrackRef, 'pointerdown', handleTrackPointerDown)
|
||||
useEventListener(horizontalTrackRef, 'mouseenter', () => handleTrackMouseEnter('horizontal'))
|
||||
useEventListener(horizontalTrackRef, 'mouseleave', () => handleTrackMouseLeave('horizontal'))
|
||||
useEventListener(horizontalTrackRef, 'pointerdown', handleHorizontalTrackPointerDown)
|
||||
|
||||
defineExpose({
|
||||
update,
|
||||
@@ -383,13 +394,11 @@ defineExpose({
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="root"
|
||||
:class="rootClasses"
|
||||
:style="{ maxHeight, height }"
|
||||
@mouseenter="activateScrollbar"
|
||||
@mousemove="activateScrollbar"
|
||||
@mouseleave="hideScrollbar"
|
||||
>
|
||||
<div ref="wrap" :class="wrapClasses">
|
||||
<div ref="wrap" :class="wrapClasses" tabindex="0">
|
||||
<div ref="view" :class="viewClass">
|
||||
<slot />
|
||||
</div>
|
||||
@@ -397,15 +406,14 @@ defineExpose({
|
||||
|
||||
<div
|
||||
v-show="canScrollY"
|
||||
ref="verticalTrack"
|
||||
aria-hidden="true"
|
||||
class="absolute top-1 z-40 w-1.5 rounded-full transition-opacity duration-200"
|
||||
:class="[
|
||||
verticalTrackInsetClass,
|
||||
verticalTrackClass,
|
||||
verticalScrollbarVisible ? 'opacity-100' : 'opacity-0',
|
||||
]"
|
||||
@mouseenter="handleTrackMouseEnter('vertical')"
|
||||
@mouseleave="handleTrackMouseLeave('vertical')"
|
||||
@pointerdown="handleTrackPointerDown"
|
||||
>
|
||||
<div
|
||||
class="w-full rounded-full bg-(--cp-scrollbar-thumb) transition-colors duration-200 hover:bg-(--cp-scrollbar-thumb-hover)"
|
||||
@@ -417,15 +425,14 @@ defineExpose({
|
||||
|
||||
<div
|
||||
v-show="canScrollX"
|
||||
ref="horizontalTrack"
|
||||
aria-hidden="true"
|
||||
class="absolute z-40 h-1.5 rounded-full transition-opacity duration-200"
|
||||
:class="[
|
||||
horizontalTrackInsetClass,
|
||||
horizontalTrackClass,
|
||||
horizontalScrollbarVisible ? 'opacity-100' : 'opacity-0',
|
||||
]"
|
||||
@mouseenter="handleTrackMouseEnter('horizontal')"
|
||||
@mouseleave="handleTrackMouseLeave('horizontal')"
|
||||
@pointerdown="handleHorizontalTrackPointerDown"
|
||||
>
|
||||
<div
|
||||
class="h-full rounded-full bg-(--cp-scrollbar-thumb) transition-colors duration-200 hover:bg-(--cp-scrollbar-thumb-hover)"
|
||||
|
||||
@@ -24,12 +24,14 @@ const props = withDefaults(
|
||||
disabled?: boolean
|
||||
placeholder?: string
|
||||
emptyText?: string
|
||||
ariaLabel?: string
|
||||
}>(),
|
||||
{
|
||||
size: 'default',
|
||||
disabled: false,
|
||||
placeholder: '请选择',
|
||||
emptyText: '暂无选项',
|
||||
ariaLabel: undefined,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -270,6 +272,7 @@ useEventListener(window, 'scroll', updatePopoverPositionThrottled, { capture: tr
|
||||
:class="triggerClasses"
|
||||
:disabled="disabled"
|
||||
role="combobox"
|
||||
:aria-label="ariaLabel"
|
||||
:aria-expanded="open"
|
||||
:aria-controls="`${selectId}-listbox`"
|
||||
:aria-activedescendant="open && activeIndex >= 0 ? optionId(activeIndex) : undefined"
|
||||
@@ -328,6 +331,7 @@ useEventListener(window, 'scroll', updatePopoverPositionThrottled, { capture: tr
|
||||
:disabled="option.disabled"
|
||||
:class="optionClasses(option, index)"
|
||||
@mouseenter="activeIndex = option.disabled ? activeIndex : index"
|
||||
@focus="activeIndex = option.disabled ? activeIndex : index"
|
||||
@mousedown.prevent
|
||||
@click="chooseOption(option, index)"
|
||||
>
|
||||
|
||||
@@ -18,8 +18,8 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'page-change': [page: number]
|
||||
'page-size-change': [pageSize: number]
|
||||
pageChange: [page: number]
|
||||
pageSizeChange: [pageSize: number]
|
||||
}>()
|
||||
|
||||
const totalPages = computed(() => getTotalPages(props.pagination))
|
||||
@@ -36,7 +36,7 @@ const pageSizeModel = computed({
|
||||
|
||||
const pageSize = Number(value)
|
||||
if (Number.isFinite(pageSize) && pageSize > 0) {
|
||||
emit('page-size-change', pageSize)
|
||||
emit('pageSizeChange', pageSize)
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -46,7 +46,7 @@ function goToPage(page: number) {
|
||||
return
|
||||
}
|
||||
|
||||
emit('page-change', page)
|
||||
emit('pageChange', page)
|
||||
}
|
||||
|
||||
function paginationButtonClass(disabled: boolean) {
|
||||
@@ -81,6 +81,7 @@ function paginationPageClass(page: number) {
|
||||
<div class="flex items-center gap-2">
|
||||
<BaseSelect
|
||||
v-model="pageSizeModel"
|
||||
aria-label="每页条数"
|
||||
:options="pageSizeOptions"
|
||||
:disabled="loading"
|
||||
size="compact"
|
||||
|
||||
@@ -53,9 +53,9 @@ const props = withDefaults(
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
'page-change': [page: number]
|
||||
'page-size-change': [pageSize: number]
|
||||
'sort-change': [sort: BaseTableSort | undefined]
|
||||
pageChange: [page: number]
|
||||
pageSizeChange: [pageSize: number]
|
||||
sortChange: [sort: BaseTableSort | undefined]
|
||||
}>()
|
||||
const slots = useSlots()
|
||||
|
||||
@@ -184,13 +184,13 @@ function toggleColumnSort(column: BaseTableColumn<Row>) {
|
||||
const key = columnSortKey(column)
|
||||
const direction = columnSortDirection(column)
|
||||
if (!direction) {
|
||||
emit('sort-change', { key, direction: 'asc' })
|
||||
emit('sortChange', { key, direction: 'asc' })
|
||||
}
|
||||
else if (direction === 'asc') {
|
||||
emit('sort-change', { key, direction: 'desc' })
|
||||
emit('sortChange', { key, direction: 'desc' })
|
||||
}
|
||||
else {
|
||||
emit('sort-change', undefined)
|
||||
emit('sortChange', undefined)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,12 +220,11 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
class="relative flex min-h-0 max-w-full flex-1 overflow-hidden pb-3"
|
||||
>
|
||||
<div class="flex min-h-0 max-w-full flex-1 flex-col overflow-hidden">
|
||||
<div ref="headerWrap" class="max-w-full overflow-hidden">
|
||||
<div class="max-w-full overflow-hidden">
|
||||
<table
|
||||
class="w-full shrink-0 table-fixed border-separate text-left"
|
||||
:class="compact ? 'border-spacing-y-0.5' : 'border-spacing-y-1'"
|
||||
:style="tableViewStyle"
|
||||
role="table"
|
||||
>
|
||||
<colgroup>
|
||||
<col
|
||||
@@ -236,7 +235,7 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
</colgroup>
|
||||
|
||||
<thead>
|
||||
<tr :class="headerRowClass" role="row">
|
||||
<tr :class="headerRowClass">
|
||||
<th
|
||||
v-for="(column, index) in computedColumns"
|
||||
:key="column.key"
|
||||
@@ -248,7 +247,6 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
fixedHeaderClass(column),
|
||||
column.headerClass,
|
||||
]"
|
||||
role="columnheader"
|
||||
scope="col"
|
||||
:aria-sort="columnAriaSort(column)"
|
||||
>
|
||||
@@ -302,7 +300,6 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
|
||||
<BaseScrollbar
|
||||
v-if="hasRows"
|
||||
ref="bodyScrollbar"
|
||||
class="min-h-0 flex-1"
|
||||
horizontal
|
||||
:max-height="maxHeight"
|
||||
@@ -310,11 +307,9 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
@scroll="handleTableScroll"
|
||||
>
|
||||
<table
|
||||
ref="tableView"
|
||||
class="w-full table-fixed border-separate text-left"
|
||||
:class="compact ? 'border-spacing-y-1' : 'border-spacing-y-2'"
|
||||
:style="tableViewStyle"
|
||||
role="table"
|
||||
>
|
||||
<colgroup>
|
||||
<col
|
||||
@@ -326,7 +321,7 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
|
||||
<tbody>
|
||||
<template v-for="(row, index) in displayRows" :key="getRowKey(row, index)">
|
||||
<tr :class="rowClass(row, index)" role="row">
|
||||
<tr :class="rowClass(row, index)">
|
||||
<td
|
||||
v-for="(column, columnIndex) in computedColumns"
|
||||
:key="column.key"
|
||||
@@ -337,7 +332,6 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
fixedBodyClass(column, row, index),
|
||||
column.cellClass,
|
||||
]"
|
||||
role="cell"
|
||||
>
|
||||
<div :class="cellContentClass(column)" :title="bodyCellTitle(column, row)">
|
||||
<slot
|
||||
@@ -352,11 +346,10 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="isRowExpanded(row, index)" role="row">
|
||||
<tr v-if="isRowExpanded(row, index)">
|
||||
<td
|
||||
:colspan="computedColumns.length"
|
||||
class="rounded-(--cp-input-radius-base) bg-(--cp-info-bg) p-0"
|
||||
role="cell"
|
||||
>
|
||||
<slot name="expanded" :row="row" :index="index" />
|
||||
</td>
|
||||
@@ -376,8 +369,8 @@ function sortButtonLabel(column: BaseTableColumn<Row>) {
|
||||
v-if="pagination"
|
||||
:pagination="pagination"
|
||||
:loading="loading"
|
||||
@page-change="emit('page-change', $event)"
|
||||
@page-size-change="emit('page-size-change', $event)"
|
||||
@page-change="emit('pageChange', $event)"
|
||||
@page-size-change="emit('pageSizeChange', $event)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -9,12 +9,16 @@ const props = withDefaults(
|
||||
disabled?: boolean
|
||||
error?: string
|
||||
size?: TextareaSize
|
||||
name?: string
|
||||
ariaLabel?: string
|
||||
}>(),
|
||||
{
|
||||
placeholder: '',
|
||||
disabled: false,
|
||||
error: undefined,
|
||||
size: 'md',
|
||||
name: undefined,
|
||||
ariaLabel: undefined,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -37,16 +41,18 @@ const textareaClasses = computed(() => [
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<label class="grid box-content gap-2 overflow-visible p-0.75">
|
||||
<div class="grid box-content gap-2 overflow-visible p-0.75">
|
||||
<textarea
|
||||
v-model="model"
|
||||
:class="textareaClasses"
|
||||
:name="name"
|
||||
:placeholder="placeholder"
|
||||
:disabled="disabled"
|
||||
:aria-label="ariaLabel"
|
||||
:aria-invalid="error ? 'true' : undefined"
|
||||
/>
|
||||
<span v-if="error" class="text-xs leading-[1.15] font-[650] text-(--cp-danger-text)">
|
||||
{{ error }}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -33,11 +33,6 @@ function elementHasSize(element: HTMLElement) {
|
||||
return element.clientWidth > 0 && element.clientHeight > 0
|
||||
}
|
||||
|
||||
function cancelPendingInit() {
|
||||
pendingInitElement.value = undefined
|
||||
pausePendingInit()
|
||||
}
|
||||
|
||||
function ensureChart(element: HTMLElement) {
|
||||
if (chart.value || !elementHasSize(element))
|
||||
return
|
||||
@@ -45,11 +40,6 @@ function ensureChart(element: HTMLElement) {
|
||||
applyOption(chartOption.value)
|
||||
}
|
||||
|
||||
function scheduleInit(element: HTMLElement) {
|
||||
pendingInitElement.value = element
|
||||
resumePendingInit()
|
||||
}
|
||||
|
||||
const { pause: pausePendingInit, resume: resumePendingInit } = useRafFn(
|
||||
() => {
|
||||
const element = pendingInitElement.value
|
||||
@@ -61,6 +51,16 @@ const { pause: pausePendingInit, resume: resumePendingInit } = useRafFn(
|
||||
{ immediate: false, once: true },
|
||||
)
|
||||
|
||||
function cancelPendingInit() {
|
||||
pendingInitElement.value = undefined
|
||||
pausePendingInit()
|
||||
}
|
||||
|
||||
function scheduleInit(element: HTMLElement) {
|
||||
pendingInitElement.value = element
|
||||
resumePendingInit()
|
||||
}
|
||||
|
||||
function resize() {
|
||||
chart.value?.resize()
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { effectScope } from 'vue'
|
||||
|
||||
import { usePagedQuery } from './usePagedQuery'
|
||||
|
||||
describe('usePagedQuery', () => {
|
||||
it('keeps the newest response when requests finish out of order', async () => {
|
||||
const first = deferred<PageResult>()
|
||||
const second = deferred<PageResult>()
|
||||
const requests = [first, second]
|
||||
const scope = effectScope()
|
||||
const query = scope.run(() =>
|
||||
usePagedQuery({
|
||||
initialPageSize: 20,
|
||||
load: () => requests.shift()!.promise,
|
||||
}),
|
||||
)!
|
||||
|
||||
const firstLoad = query.execute()
|
||||
query.page.value = 2
|
||||
const secondLoad = query.execute()
|
||||
second.resolve(pageResult('new', 2))
|
||||
await secondLoad
|
||||
first.resolve(pageResult('stale', 1))
|
||||
await firstLoad
|
||||
|
||||
expect(query.items.value).toEqual([{ id: 'new' }])
|
||||
expect(query.page.value).toBe(2)
|
||||
scope.stop()
|
||||
})
|
||||
|
||||
it('moves to the last valid page after deleting the final row', async () => {
|
||||
const scope = effectScope()
|
||||
const results = [
|
||||
{ items: [], page: { page: 3, pageSize: 20, total: 21, totalPages: 2 } },
|
||||
pageResult('last', 2),
|
||||
]
|
||||
const query = scope.run(() =>
|
||||
usePagedQuery({
|
||||
initialPageSize: 20,
|
||||
load: async () => results.shift()!,
|
||||
}),
|
||||
)!
|
||||
query.page.value = 3
|
||||
|
||||
await query.execute()
|
||||
|
||||
expect(query.page.value).toBe(2)
|
||||
expect(query.items.value).toEqual([{ id: 'last' }])
|
||||
scope.stop()
|
||||
})
|
||||
})
|
||||
|
||||
interface PageResult {
|
||||
items: Array<{ id: string }>
|
||||
page: {
|
||||
page: number
|
||||
pageSize: number
|
||||
total: number
|
||||
totalPages: number
|
||||
}
|
||||
}
|
||||
|
||||
function pageResult(id: string, page: number): PageResult {
|
||||
return {
|
||||
items: [{ id }],
|
||||
page: { page, pageSize: 20, total: 40, totalPages: 2 },
|
||||
}
|
||||
}
|
||||
|
||||
function deferred<Value>() {
|
||||
let resolve!: (value: Value) => void
|
||||
const promise = new Promise<Value>((resolvePromise) => {
|
||||
resolve = resolvePromise
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
@@ -35,7 +35,6 @@ const PANEL_CLASS = [
|
||||
'items-center',
|
||||
'gap-2.5',
|
||||
'rounded-xl',
|
||||
'bg-(--cp-bg-surface)',
|
||||
'py-2.25',
|
||||
'pr-3.5',
|
||||
'pl-3',
|
||||
@@ -43,7 +42,6 @@ const PANEL_CLASS = [
|
||||
'leading-[1.15]',
|
||||
'font-[760]',
|
||||
'text-(--cp-text-secondary)',
|
||||
'shadow-(--cp-shadow-popover)',
|
||||
].join(' ')
|
||||
const MARK_CLASS = [
|
||||
'inline-block',
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
<script setup lang="ts">
|
||||
import type { getSystemUpdateDetail } from '@/api'
|
||||
import type { SystemUpdateEvent } from '@/api/streams/system-update'
|
||||
import {
|
||||
ArrowUpCircle,
|
||||
CheckCircle2,
|
||||
@@ -48,7 +46,7 @@ const { loadSystem, checkUpdates, updateNow, restartNow } = systemUpdateStore
|
||||
|
||||
const updateLogScrollbar = useTemplateRef<InstanceType<typeof BaseScrollbar>>('updateLogScrollbar')
|
||||
const updateConfirmOpen = shallowRef(false)
|
||||
const updateConfirmInfo = shallowRef<Awaited<ReturnType<typeof getSystemUpdateDetail>> | null>(null)
|
||||
const updateConfirmInfo = shallowRef<any>(null)
|
||||
const updateConfirmPreviousTarget = shallowRef('')
|
||||
const preparingUpdate = shallowRef(false)
|
||||
|
||||
@@ -185,7 +183,7 @@ function formatLogTime(value: string) {
|
||||
return date.toLocaleTimeString('zh-CN', { hour12: false })
|
||||
}
|
||||
|
||||
function logMarkerClass(level: SystemUpdateEvent['level']) {
|
||||
function logMarkerClass(level: string) {
|
||||
if (level === 'success')
|
||||
return 'text-(--cp-success)'
|
||||
if (level === 'warning')
|
||||
@@ -195,7 +193,7 @@ function logMarkerClass(level: SystemUpdateEvent['level']) {
|
||||
return 'text-(--cp-info)'
|
||||
}
|
||||
|
||||
function logTextClass(level: SystemUpdateEvent['level']) {
|
||||
function logTextClass(level: string) {
|
||||
if (level === 'success')
|
||||
return 'text-(--cp-success)'
|
||||
if (level === 'warning')
|
||||
|
||||
+7
-10
@@ -1,21 +1,18 @@
|
||||
import { createApp } from 'vue'
|
||||
import { setUnauthorizedHandler } from './api/request'
|
||||
import App from './App.vue'
|
||||
|
||||
import { loading } from './directives/loading'
|
||||
import { authPlugin } from './plugins/auth'
|
||||
import { router } from './router'
|
||||
import { pinia } from './stores'
|
||||
import { useAuthStore } from './stores/modules/auth'
|
||||
import '@fontsource-variable/inter'
|
||||
import '@fontsource-variable/jetbrains-mono'
|
||||
|
||||
import './styles/index.css'
|
||||
|
||||
setUnauthorizedHandler(async () => {
|
||||
useAuthStore(pinia).invalidateSession()
|
||||
if (router.currentRoute.value.path !== '/login') {
|
||||
await router.replace({ name: 'login' })
|
||||
}
|
||||
})
|
||||
|
||||
createApp(App).directive('loading', loading).use(pinia).use(router).mount('#app')
|
||||
createApp(App)
|
||||
.directive('loading', loading)
|
||||
.use(pinia)
|
||||
.use(router)
|
||||
.use(authPlugin)
|
||||
.mount('#app')
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
export function delay(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
window.setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
|
||||
export function reloadPage() {
|
||||
window.location.reload()
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Plugin } from 'vue'
|
||||
|
||||
import { setUnauthorizedHandler } from '@/api/request'
|
||||
import { router } from '@/router'
|
||||
import { pinia } from '@/stores'
|
||||
import { useAuthStore } from '@/stores/modules/auth'
|
||||
|
||||
export const authPlugin: Plugin = {
|
||||
install() {
|
||||
const authStore = useAuthStore(pinia)
|
||||
|
||||
setUnauthorizedHandler(async () => {
|
||||
authStore.invalidateSession()
|
||||
if (router.currentRoute.value.path !== '/login')
|
||||
await router.replace({ name: 'login' })
|
||||
})
|
||||
},
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import type { SystemUpdateEvent } from '@/api/streams/system-update'
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { reduceSystemUpdateLogs } from './system-update-reducer'
|
||||
|
||||
describe('system update event reducer', () => {
|
||||
it('deduplicates reconnect events and retains the newest bounded window', () => {
|
||||
const first = event('1', 'first')
|
||||
const replacement = event('1', 'replacement')
|
||||
const second = event('2', 'second')
|
||||
|
||||
const logs = reduceSystemUpdateLogs(
|
||||
reduceSystemUpdateLogs(reduceSystemUpdateLogs([], first, 2), second, 2),
|
||||
replacement,
|
||||
2,
|
||||
)
|
||||
|
||||
expect(logs.map(log => [log.id, log.message])).toEqual([
|
||||
['2', 'second'],
|
||||
['1', 'replacement'],
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
function event(id: string, message: string): SystemUpdateEvent {
|
||||
return {
|
||||
id,
|
||||
level: 'info',
|
||||
message,
|
||||
at: '2026-07-17T00:00:00Z',
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { SystemUpdateEvent } from '@/api/streams/system-update'
|
||||
|
||||
export function reduceSystemUpdateLogs(
|
||||
logs: SystemUpdateEvent[],
|
||||
event: SystemUpdateEvent,
|
||||
limit = 200,
|
||||
) {
|
||||
const withoutDuplicate = logs.filter(log => log.id !== event.id)
|
||||
return [...withoutDuplicate, event].slice(-limit)
|
||||
}
|
||||
@@ -1,26 +1,23 @@
|
||||
import type { SystemUpdateEvent } from '@/api/streams/system-update'
|
||||
import { useEventSource } from '@vueuse/core'
|
||||
import { delay } from 'es-toolkit'
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
import { computed, ref, shallowRef } from 'vue'
|
||||
import { computed, ref, shallowRef, watch } from 'vue'
|
||||
import {
|
||||
getSystemUpdateDetail,
|
||||
getSystemVersion,
|
||||
performSystemUpdate,
|
||||
restartSystem,
|
||||
} from '@/api'
|
||||
import { API_BASE_URL } from '@/api/constants'
|
||||
import { ApiError } from '@/api/request'
|
||||
import { openSystemUpdateStream } from '@/api/streams/system-update'
|
||||
import { delay, reloadPage } from '@/platform/browser'
|
||||
import { errorMessage } from '@/utils/async'
|
||||
import { reduceSystemUpdateLogs } from './system-update-reducer'
|
||||
|
||||
const maxUpdateLogs = 200
|
||||
const restartReadyTimeoutMs = 60_000
|
||||
const restartProbeTimeoutMs = 2_000
|
||||
const restartReadyPollIntervalMs = 500
|
||||
|
||||
type SystemUpdateStream = NonNullable<ReturnType<typeof openSystemUpdateStream>>
|
||||
|
||||
export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
const version = shallowRef<Awaited<ReturnType<typeof getSystemVersion>> | null>(null)
|
||||
const updateInfo = shallowRef<Awaited<ReturnType<typeof getSystemUpdateDetail>> | null>(null)
|
||||
@@ -32,12 +29,26 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
const updateSuccess = shallowRef(false)
|
||||
const needRestart = shallowRef(false)
|
||||
const loadedOnce = shallowRef(false)
|
||||
const updateLogs = ref<SystemUpdateEvent[]>([])
|
||||
const updateLogs = ref<any[]>([])
|
||||
const updateStreaming = shallowRef(false)
|
||||
const updateStreamError = shallowRef('')
|
||||
const restartTargetVersion = shallowRef('')
|
||||
const {
|
||||
data: updateEventMessage,
|
||||
status: updateEventStatus,
|
||||
error: updateEventError,
|
||||
eventSource: updateEventSource,
|
||||
open: openUpdateEventSource,
|
||||
close: closeUpdateEventSource,
|
||||
} = useEventSource(`${API_BASE_URL}/api/admin/system/update-events`, ['update'], {
|
||||
autoConnect: false,
|
||||
immediate: false,
|
||||
withCredentials: true,
|
||||
serializer: {
|
||||
read: raw => ({ raw }),
|
||||
},
|
||||
})
|
||||
|
||||
let updateEventSource: SystemUpdateStream | null = null
|
||||
let loadVersionPromise: ReturnType<typeof getSystemVersion> | undefined
|
||||
let loadSystemPromise: Promise<void> | undefined
|
||||
|
||||
@@ -60,8 +71,9 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
restartTargetVersion.value = ''
|
||||
}
|
||||
|
||||
function appendUpdateLog(log: SystemUpdateEvent) {
|
||||
updateLogs.value = reduceSystemUpdateLogs(updateLogs.value, log, maxUpdateLogs)
|
||||
function appendUpdateLog(log: any) {
|
||||
const logs = updateLogs.value.filter(item => item.id !== log.id)
|
||||
updateLogs.value = [...logs, log].slice(-maxUpdateLogs)
|
||||
}
|
||||
|
||||
function clearUpdateLogs() {
|
||||
@@ -69,56 +81,48 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
updateStreamError.value = ''
|
||||
}
|
||||
|
||||
watch(updateEventStatus, (status) => {
|
||||
updateStreaming.value = status === 'OPEN'
|
||||
if (status === 'OPEN')
|
||||
updateStreamError.value = ''
|
||||
})
|
||||
|
||||
watch(updateEventError, (error) => {
|
||||
if (error)
|
||||
updateStreamError.value = '更新日志连接中断'
|
||||
})
|
||||
|
||||
watch(updateEventMessage, (message) => {
|
||||
if (!message?.raw)
|
||||
return
|
||||
try {
|
||||
const event = JSON.parse(message.raw)
|
||||
appendUpdateLog(event)
|
||||
if (event.terminal)
|
||||
disconnectUpdateEvents()
|
||||
}
|
||||
catch {
|
||||
updateStreamError.value = '更新日志解析失败'
|
||||
}
|
||||
})
|
||||
|
||||
function connectUpdateEvents(force = false) {
|
||||
if (force) {
|
||||
disconnectUpdateEvents()
|
||||
}
|
||||
else if (updateEventSource) {
|
||||
else if (updateEventSource.value) {
|
||||
return
|
||||
}
|
||||
|
||||
updateStreamError.value = ''
|
||||
let source: SystemUpdateStream | null = null
|
||||
source = openSystemUpdateStream({
|
||||
onOpen: () => {
|
||||
if (updateEventSource !== source)
|
||||
return
|
||||
updateStreaming.value = true
|
||||
updateStreamError.value = ''
|
||||
},
|
||||
onEvent: (event) => {
|
||||
if (updateEventSource !== source)
|
||||
return
|
||||
appendUpdateLog(event)
|
||||
if (event.terminal)
|
||||
disconnectUpdateEvents(source)
|
||||
},
|
||||
onError: (closed) => {
|
||||
if (updateEventSource !== source)
|
||||
return
|
||||
updateStreaming.value = false
|
||||
updateStreamError.value = '更新日志连接中断'
|
||||
if (closed)
|
||||
updateEventSource = null
|
||||
},
|
||||
onParseError: () => {
|
||||
if (updateEventSource === source)
|
||||
updateStreamError.value = '更新日志解析失败'
|
||||
},
|
||||
})
|
||||
if (!source) {
|
||||
openUpdateEventSource()
|
||||
if (!updateEventSource.value) {
|
||||
updateStreamError.value = '当前浏览器不支持实时更新日志'
|
||||
return
|
||||
}
|
||||
updateEventSource = source
|
||||
}
|
||||
|
||||
function disconnectUpdateEvents(source = updateEventSource) {
|
||||
source?.close()
|
||||
if (source && updateEventSource !== source)
|
||||
return
|
||||
updateEventSource = null
|
||||
updateStreaming.value = false
|
||||
function disconnectUpdateEvents() {
|
||||
closeUpdateEventSource()
|
||||
}
|
||||
|
||||
async function loadSystem(refresh = false) {
|
||||
@@ -127,7 +131,7 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
|
||||
loading.value = true
|
||||
loadSystemPromise = (async () => {
|
||||
updateInfo.value = await getSystemUpdateDetail(refresh)
|
||||
updateInfo.value = await getSystemUpdateDetail({ refresh })
|
||||
if (!version.value)
|
||||
version.value = await getSystemVersion()
|
||||
loadedOnce.value = true
|
||||
@@ -164,7 +168,7 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
checking.value = true
|
||||
resetUpdateResult()
|
||||
try {
|
||||
updateInfo.value = await getSystemUpdateDetail(refresh)
|
||||
updateInfo.value = await getSystemUpdateDetail({ refresh })
|
||||
if (!version.value)
|
||||
version.value = await getSystemVersion()
|
||||
loadedOnce.value = true
|
||||
@@ -187,7 +191,7 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
updateError.value = ''
|
||||
updateSuccess.value = false
|
||||
try {
|
||||
const result = await performSystemUpdate(confirmedTargetVersion)
|
||||
const result = await performSystemUpdate({ targetVersion: confirmedTargetVersion })
|
||||
updateSuccess.value = true
|
||||
needRestart.value = result.needRestart
|
||||
restartTargetVersion.value = result.needRestart ? normalizeVersion(result.targetVersion) : ''
|
||||
@@ -219,9 +223,9 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const readyVersion = await getSystemVersion({ timeoutMs: restartProbeTimeoutMs })
|
||||
const readyVersion = await getSystemVersion(restartProbeTimeoutMs)
|
||||
if (normalizeVersion(readyVersion.version) === expectedVersion) {
|
||||
reloadPage()
|
||||
window.location.reload()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useScrollLock } from '@vueuse/core'
|
||||
|
||||
const bodyScrollLocked = useScrollLock(document.body)
|
||||
let lockCount = 0
|
||||
|
||||
export function lockBodyScroll() {
|
||||
lockCount += 1
|
||||
if (lockCount === 1)
|
||||
bodyScrollLocked.value = true
|
||||
}
|
||||
|
||||
export function unlockBodyScroll() {
|
||||
lockCount = Math.max(0, lockCount - 1)
|
||||
if (lockCount === 0)
|
||||
bodyScrollLocked.value = false
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
let lockCount = 0
|
||||
let previousOverflow = ''
|
||||
|
||||
export function lockBodyScroll() {
|
||||
if (lockCount === 0) {
|
||||
previousOverflow = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
}
|
||||
lockCount += 1
|
||||
}
|
||||
|
||||
export function unlockBodyScroll() {
|
||||
lockCount = Math.max(0, lockCount - 1)
|
||||
if (lockCount === 0)
|
||||
document.body.style.overflow = previousOverflow
|
||||
}
|
||||
@@ -63,7 +63,9 @@ function connectionLogClass(tone: string) {
|
||||
<section class="rounded-(--cp-card-radius) bg-(--cp-bg-subtle) px-4 py-3">
|
||||
<div class="grid gap-2">
|
||||
<div class="flex min-h-8 items-center justify-between gap-3">
|
||||
<label class="text-[12px] font-[760] text-(--cp-text-muted)">测试模型</label>
|
||||
<span class="text-[12px] font-[760] text-(--cp-text-muted)">
|
||||
测试模型
|
||||
</span>
|
||||
<BaseButton
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -80,6 +82,7 @@ function connectionLogClass(tone: string) {
|
||||
</div>
|
||||
<BaseSelect
|
||||
v-model="selectedModel"
|
||||
aria-label="测试模型"
|
||||
:options="modelOptions"
|
||||
:disabled="status === 'running' || loadingModels || refreshingModels"
|
||||
:placeholder="loadingModels ? '加载模型中...' : '选择上游模型'"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import type { useAccountOnboarding } from '../composables/useAccountOnboarding'
|
||||
import type { AccountRow } from '../quota'
|
||||
import type { AccountRow } from '../constants'
|
||||
import { Copy, KeyRound, Upload } from '@lucide/vue'
|
||||
|
||||
import { useClipboard, useFileDialog } from '@vueuse/core'
|
||||
@@ -184,6 +184,7 @@ async function copyOAuthAuthUrl() {
|
||||
<BaseFormItem label="Token" required>
|
||||
<BaseTextarea
|
||||
v-model="tokenText"
|
||||
aria-label="Token"
|
||||
size="md"
|
||||
placeholder="eyJ... rt_..."
|
||||
:disabled="saving"
|
||||
@@ -251,6 +252,7 @@ async function copyOAuthAuthUrl() {
|
||||
<BaseFormItem label="回调地址" required>
|
||||
<BaseTextarea
|
||||
v-model="oauthCallback"
|
||||
aria-label="回调地址"
|
||||
size="sm"
|
||||
placeholder="http://localhost:1455/auth/callback?code=...&state=..."
|
||||
:disabled="saving"
|
||||
@@ -260,7 +262,11 @@ async function copyOAuthAuthUrl() {
|
||||
</div>
|
||||
|
||||
<BaseForm v-else>
|
||||
<BaseFormItem label="JSON 内容" required :error="fileError || undefined">
|
||||
<BaseFormItem
|
||||
label="JSON 内容"
|
||||
required
|
||||
:error="fileError || undefined"
|
||||
>
|
||||
<template #extra>
|
||||
<BaseButton variant="default" size="sm" :disabled="saving" @click="openImportFile()">
|
||||
<template #icon>
|
||||
@@ -271,6 +277,7 @@ async function copyOAuthAuthUrl() {
|
||||
</template>
|
||||
<BaseTextarea
|
||||
v-model="importText"
|
||||
aria-label="JSON 内容"
|
||||
size="lg"
|
||||
placeholder="{"accounts":[...]}"
|
||||
:disabled="saving"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountRow } from '../quota'
|
||||
import type { AccountRow } from '../constants'
|
||||
import { RefreshCw } from '@lucide/vue'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import BaseButton from '@/components/base/BaseButton.vue'
|
||||
import { orderedPanelQuotaWindows } from '../quota'
|
||||
import { orderedPanelQuotaWindows } from '../constants'
|
||||
import AccountPlanBadge from './AccountPlanBadge.vue'
|
||||
import AccountQuotaWindow from './AccountQuotaWindow.vue'
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountRow } from '../quota'
|
||||
import type { AccountRow } from '../constants'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import {
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
quotaWindowPercentTextClass,
|
||||
shouldShowQuotaWindowLocalUsage,
|
||||
visibleSummaryQuotaWindows,
|
||||
} from '../quota'
|
||||
} from '../constants'
|
||||
|
||||
const props = defineProps<{
|
||||
account: AccountRow
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountQuotaWindow } from '../quota'
|
||||
import type { AccountQuotaWindow } from '../constants'
|
||||
import {
|
||||
|
||||
quotaWindowBarClass,
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
quotaWindowLocalUsageDisplay,
|
||||
quotaWindowPercentTextClass,
|
||||
shouldShowQuotaWindowLocalUsage,
|
||||
} from '../quota'
|
||||
} from '../constants'
|
||||
|
||||
defineProps<{
|
||||
window: AccountQuotaWindow
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountRow } from '../quota'
|
||||
import type { AccountRow } from '../constants'
|
||||
import { KeyRound, LoaderCircle, MoreHorizontal, Power, RefreshCw, Trash2, Wifi } from '@lucide/vue'
|
||||
|
||||
import { computed } from 'vue'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountRow } from '../quota'
|
||||
import type { AccountRow } from '../constants'
|
||||
|
||||
defineProps<{
|
||||
account: AccountRow
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import type { getAccounts } from '@/api'
|
||||
import type { AccountConnectionEvent } from '@/api/streams/account-connection'
|
||||
import { CheckCircle2, Clock3, Wifi, XCircle } from '@lucide/vue'
|
||||
import { useEventSource } from '@vueuse/core'
|
||||
|
||||
import { clamp } from 'es-toolkit'
|
||||
import { computed, onBeforeUnmount, ref, shallowRef, watch } from 'vue'
|
||||
import { getAccountModels, refreshAccountModels } from '@/api'
|
||||
import {
|
||||
|
||||
openAccountConnectionStream,
|
||||
} from '@/api/streams/account-connection'
|
||||
import { API_BASE_URL } from '@/api/constants'
|
||||
import { toast } from '@/components/base/BaseToast'
|
||||
import { errorMessage, withMinimumDuration } from '@/utils/async'
|
||||
import { formatDateTime, formatTime } from '@/utils/date'
|
||||
@@ -21,8 +17,6 @@ interface ConnectionTestRun {
|
||||
type ConnectionTestStatus = 'idle' | 'running' | 'success' | 'error'
|
||||
type ConnectionTestLogTone = 'normal' | 'info' | 'success' | 'danger'
|
||||
|
||||
type ConnectionTestAccount = Awaited<ReturnType<typeof getAccounts>>['items'][number]
|
||||
|
||||
interface ConnectionTestModelOption {
|
||||
label: string
|
||||
value: string
|
||||
@@ -36,10 +30,9 @@ interface ConnectionTestLog {
|
||||
detail: string
|
||||
}
|
||||
|
||||
type ConnectionTestRequestPayload = Extract<
|
||||
AccountConnectionEvent,
|
||||
{ type: 'request' }
|
||||
>['payload']
|
||||
interface ConnectionTestRequestPayload {
|
||||
input?: Array<{ content?: Array<{ type?: string, text?: string }> }>
|
||||
}
|
||||
|
||||
interface AccountConnectionTestOptions {
|
||||
onAccountStatus: (accountId: string, status: string) => void
|
||||
@@ -47,7 +40,7 @@ interface AccountConnectionTestOptions {
|
||||
|
||||
export function useAccountConnectionTest(options: AccountConnectionTestOptions) {
|
||||
const showConnectionTestModal = shallowRef(false)
|
||||
const testingAccount = shallowRef<ConnectionTestAccount | null>(null)
|
||||
const testingAccount = shallowRef<any>(null)
|
||||
const connectionTestStatus = shallowRef<ConnectionTestStatus>('idle')
|
||||
const connectionTestModel = shallowRef('')
|
||||
const connectionTestContent = shallowRef('')
|
||||
@@ -61,10 +54,24 @@ export function useAccountConnectionTest(options: AccountConnectionTestOptions)
|
||||
const refreshingConnectionTestModels = shallowRef(false)
|
||||
const connectionTestSelectedModel = shallowRef('')
|
||||
const connectionTestModelOptions = ref<ConnectionTestModelOption[]>([])
|
||||
const connectionTestStreamUrl = shallowRef<string>()
|
||||
const {
|
||||
data: connectionTestStreamMessage,
|
||||
error: connectionTestStreamError,
|
||||
eventSource: connectionTestEventSource,
|
||||
open: openConnectionTestEventSource,
|
||||
close: closeConnectionTestEventSource,
|
||||
} = useEventSource(connectionTestStreamUrl, [], {
|
||||
autoConnect: false,
|
||||
immediate: false,
|
||||
withCredentials: true,
|
||||
serializer: {
|
||||
read: raw => ({ raw }),
|
||||
},
|
||||
})
|
||||
|
||||
let connectionTestStartedAtMs = 0
|
||||
let connectionTestRun: ConnectionTestRun | undefined
|
||||
let connectionTestSource: ReturnType<typeof openAccountConnectionStream> | null = null
|
||||
|
||||
const connectionTestStatusView = computed(() => {
|
||||
if (connectionTestStatus.value === 'running') {
|
||||
@@ -103,7 +110,7 @@ export function useAccountConnectionTest(options: AccountConnectionTestOptions)
|
||||
}
|
||||
})
|
||||
|
||||
function openConnectionTest(account: ConnectionTestAccount) {
|
||||
function openConnectionTest(account: any) {
|
||||
abortConnectionTest()
|
||||
testingAccount.value = account
|
||||
connectionTestSelectedModel.value = ''
|
||||
@@ -209,8 +216,7 @@ export function useAccountConnectionTest(options: AccountConnectionTestOptions)
|
||||
function clearConnectionTestRun() {
|
||||
const run = connectionTestRun
|
||||
connectionTestRun = undefined
|
||||
connectionTestSource?.close()
|
||||
connectionTestSource = null
|
||||
closeConnectionTestEventSource()
|
||||
if (run) {
|
||||
const next = new Set(testingConnectionIds.value)
|
||||
next.delete(run.accountId)
|
||||
@@ -228,7 +234,7 @@ export function useAccountConnectionTest(options: AccountConnectionTestOptions)
|
||||
clearConnectionTestRun()
|
||||
}
|
||||
|
||||
function handleConnectionTestEvent(event: AccountConnectionEvent) {
|
||||
function handleConnectionTestEvent(event: any) {
|
||||
if (event.type === 'test_start') {
|
||||
connectionTestModel.value = event.model || connectionTestModel.value
|
||||
appendConnectionTestLog(`开始测试 ${connectionTestModel.value || '未选择模型'}`, 'info')
|
||||
@@ -299,15 +305,15 @@ export function useAccountConnectionTest(options: AccountConnectionTestOptions)
|
||||
}
|
||||
}
|
||||
|
||||
function applyConnectionTestModels(
|
||||
result: Awaited<ReturnType<typeof getAccountModels>>,
|
||||
preserveSelection = false,
|
||||
) {
|
||||
function applyConnectionTestModels(result: any, preserveSelection = false) {
|
||||
const previousSelection = preserveSelection ? connectionTestSelectedModel.value : ''
|
||||
connectionTestModelOptions.value = (result.models ?? []).map(model => ({
|
||||
label: model.label || model.id,
|
||||
value: model.id,
|
||||
}))
|
||||
connectionTestModelOptions.value = []
|
||||
for (const model of result.models ?? []) {
|
||||
connectionTestModelOptions.value.push({
|
||||
label: model.label || model.id,
|
||||
value: model.id,
|
||||
})
|
||||
}
|
||||
connectionTestSelectedModel.value = connectionTestModelOptions.value.some(
|
||||
model => model.value === previousSelection,
|
||||
)
|
||||
@@ -364,15 +370,15 @@ export function useAccountConnectionTest(options: AccountConnectionTestOptions)
|
||||
accountId: account.id,
|
||||
resolve,
|
||||
}
|
||||
connectionTestSource = openAccountConnectionStream({
|
||||
accountId: account.id,
|
||||
const params = new URLSearchParams({
|
||||
id: account.id,
|
||||
modelId: connectionTestSelectedModel.value,
|
||||
onEvent: handleConnectionTestEvent,
|
||||
onError: () => {
|
||||
if (connectionTestRun)
|
||||
failConnectionTest('测试连接已断开')
|
||||
},
|
||||
})
|
||||
connectionTestStreamUrl.value
|
||||
= `${API_BASE_URL}/api/admin/accounts/test?${params}`
|
||||
openConnectionTestEventSource()
|
||||
if (!connectionTestEventSource.value)
|
||||
failConnectionTest('当前浏览器不支持连接测试')
|
||||
}),
|
||||
)
|
||||
if (connectionTestStatus.value === 'running') {
|
||||
@@ -391,6 +397,22 @@ export function useAccountConnectionTest(options: AccountConnectionTestOptions)
|
||||
}
|
||||
}
|
||||
|
||||
watch(connectionTestStreamMessage, (message) => {
|
||||
if (!message?.raw || !connectionTestRun)
|
||||
return
|
||||
try {
|
||||
handleConnectionTestEvent(JSON.parse(message.raw))
|
||||
}
|
||||
catch {
|
||||
failConnectionTest('测试响应解析失败')
|
||||
}
|
||||
})
|
||||
|
||||
watch(connectionTestStreamError, (error) => {
|
||||
if (error && connectionTestRun)
|
||||
failConnectionTest('测试连接已断开')
|
||||
})
|
||||
|
||||
watch(showConnectionTestModal, (open) => {
|
||||
if (!open) {
|
||||
abortConnectionTest()
|
||||
|
||||
@@ -121,7 +121,10 @@ export function useAccountMutations(options: {
|
||||
|
||||
await exportingAccountsAction.run(
|
||||
async () => {
|
||||
const payload = await exportAccounts({ ids: selected.join(',') })
|
||||
const payload = await exportAccounts({
|
||||
ids: selected.join(','),
|
||||
confirm: 'export_sensitive_accounts',
|
||||
})
|
||||
await downloadJson(payload, exportFileName(selected.length))
|
||||
toast.success(`已导出 ${selected.length} 个账号`)
|
||||
},
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
import type { AccountRow } from './quota'
|
||||
import type { getAccounts } from '@/api'
|
||||
import type { BaseTableColumn } from '@/components/base/BaseTable/columns'
|
||||
import { clamp } from 'es-toolkit'
|
||||
|
||||
export type AccountRow = Awaited<ReturnType<typeof getAccounts>>['items'][number]
|
||||
export type AccountQuotaWindow = AccountRow['quota']['windows'][number]
|
||||
|
||||
const summaryGroupOrder = new Map([
|
||||
['shortTerm', 0],
|
||||
['monthly', 1],
|
||||
])
|
||||
|
||||
const panelGroupOrder = new Map([
|
||||
['monthly', 0],
|
||||
['shortTerm', 1],
|
||||
['other', 2],
|
||||
])
|
||||
|
||||
const relaxedCellClass = 'py-3 align-middle'
|
||||
|
||||
@@ -107,3 +122,60 @@ export const accountStatusFilterOptions = [
|
||||
{ label: statusLabels.disabled, value: 'disabled' },
|
||||
{ label: statusLabels.banned, value: 'banned' },
|
||||
]
|
||||
|
||||
export function visibleSummaryQuotaWindows(windows: AccountQuotaWindow[]) {
|
||||
const known = [...windows]
|
||||
.filter(window => summaryGroupOrder.has(window.group))
|
||||
.sort((left, right) => groupOrder(left, summaryGroupOrder) - groupOrder(right, summaryGroupOrder))
|
||||
return known.length > 0 ? known : windows
|
||||
}
|
||||
|
||||
export function orderedPanelQuotaWindows(windows: AccountQuotaWindow[]) {
|
||||
return [...windows].sort(
|
||||
(left, right) => groupOrder(left, panelGroupOrder) - groupOrder(right, panelGroupOrder),
|
||||
)
|
||||
}
|
||||
|
||||
export function quotaWindowPercent(window: AccountQuotaWindow) {
|
||||
return clamp(window.usedPercent ?? 0, 0, 100)
|
||||
}
|
||||
|
||||
export function quotaWindowBarStyle(window: AccountQuotaWindow, minimumWidth = '8px') {
|
||||
const percent = quotaWindowPercent(window)
|
||||
return {
|
||||
width: `${percent}%`,
|
||||
minWidth: percent > 0 ? minimumWidth : '0',
|
||||
}
|
||||
}
|
||||
|
||||
export function quotaWindowBarClass(window: AccountQuotaWindow) {
|
||||
if (window.usedPercent === null)
|
||||
return 'bg-(--cp-default-border-hover)'
|
||||
if (window.usedPercent >= 95)
|
||||
return 'bg-(--cp-danger)'
|
||||
if (window.usedPercent >= 80)
|
||||
return 'bg-(--cp-warning)'
|
||||
return 'bg-(--cp-success)'
|
||||
}
|
||||
|
||||
export function quotaWindowPercentTextClass(window: AccountQuotaWindow) {
|
||||
if (window.usedPercent === null)
|
||||
return 'text-(--cp-text-muted)'
|
||||
if (window.usedPercent >= 95)
|
||||
return 'text-(--cp-danger-text)'
|
||||
if (window.usedPercent >= 80)
|
||||
return 'text-(--cp-warning-text)'
|
||||
return 'text-(--cp-success-text)'
|
||||
}
|
||||
|
||||
export function quotaWindowLocalUsageDisplay(window: AccountQuotaWindow) {
|
||||
return window.localUsage?.totalTokensDisplay || '-'
|
||||
}
|
||||
|
||||
export function shouldShowQuotaWindowLocalUsage(window: AccountQuotaWindow) {
|
||||
return (window.localUsage?.totalTokens ?? 0) > 0
|
||||
}
|
||||
|
||||
function groupOrder(window: AccountQuotaWindow, order: Map<string, number>) {
|
||||
return order.get(window.group) ?? order.size
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { AccountQuotaWindow } from './quota'
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
|
||||
orderedPanelQuotaWindows,
|
||||
quotaWindowBarClass,
|
||||
quotaWindowPercent,
|
||||
quotaWindowPercentTextClass,
|
||||
visibleSummaryQuotaWindows,
|
||||
} from './quota'
|
||||
|
||||
describe('account quota presenter', () => {
|
||||
it('uses backend window groups instead of inferring semantics from duration', () => {
|
||||
const windows = [window('other', 7), window('monthly', 20), window('shortTerm', 30)]
|
||||
|
||||
expect(visibleSummaryQuotaWindows(windows).map(item => item.group)).toEqual([
|
||||
'shortTerm',
|
||||
'monthly',
|
||||
])
|
||||
expect(orderedPanelQuotaWindows(windows).map(item => item.group)).toEqual([
|
||||
'monthly',
|
||||
'shortTerm',
|
||||
'other',
|
||||
])
|
||||
})
|
||||
|
||||
it('clamps percentages and applies stable threshold tones', () => {
|
||||
expect(quotaWindowPercent(window('shortTerm', 120))).toBe(100)
|
||||
expect(quotaWindowBarClass(window('shortTerm', 95))).toBe('bg-(--cp-danger)')
|
||||
expect(quotaWindowPercentTextClass(window('shortTerm', 80))).toBe(
|
||||
'text-(--cp-warning-text)',
|
||||
)
|
||||
expect(quotaWindowBarClass(window('shortTerm', null))).toBe(
|
||||
'bg-(--cp-default-border-hover)',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
function window(group: AccountQuotaWindow['group'], usedPercent: number | null): AccountQuotaWindow {
|
||||
return {
|
||||
key: `${group}-${usedPercent}`,
|
||||
group,
|
||||
windowSeconds: null,
|
||||
labelDisplay: group,
|
||||
usedPercent,
|
||||
usedPercentDisplay: usedPercent === null ? '-' : `${usedPercent}%`,
|
||||
resetAtDisplay: '-',
|
||||
windowUsedDisplay: '-',
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import type { getAccounts } from '@/api'
|
||||
|
||||
import { clamp } from 'es-toolkit'
|
||||
|
||||
export type AccountRow = Awaited<ReturnType<typeof getAccounts>>['items'][number]
|
||||
export type AccountQuotaWindow = AccountRow['quota']['windows'][number]
|
||||
|
||||
const summaryGroupOrder = new Map([
|
||||
['shortTerm', 0],
|
||||
['monthly', 1],
|
||||
])
|
||||
|
||||
const panelGroupOrder = new Map([
|
||||
['monthly', 0],
|
||||
['shortTerm', 1],
|
||||
['other', 2],
|
||||
])
|
||||
|
||||
export function visibleSummaryQuotaWindows(windows: AccountQuotaWindow[]) {
|
||||
const known = [...windows]
|
||||
.filter(window => summaryGroupOrder.has(window.group))
|
||||
.sort((left, right) => groupOrder(left, summaryGroupOrder) - groupOrder(right, summaryGroupOrder))
|
||||
return known.length > 0 ? known : windows
|
||||
}
|
||||
|
||||
export function orderedPanelQuotaWindows(windows: AccountQuotaWindow[]) {
|
||||
return [...windows].sort(
|
||||
(left, right) => groupOrder(left, panelGroupOrder) - groupOrder(right, panelGroupOrder),
|
||||
)
|
||||
}
|
||||
|
||||
export function quotaWindowPercent(window: AccountQuotaWindow) {
|
||||
return clamp(window.usedPercent ?? 0, 0, 100)
|
||||
}
|
||||
|
||||
export function quotaWindowBarStyle(window: AccountQuotaWindow, minimumWidth = '8px') {
|
||||
const percent = quotaWindowPercent(window)
|
||||
return {
|
||||
width: `${percent}%`,
|
||||
minWidth: percent > 0 ? minimumWidth : '0',
|
||||
}
|
||||
}
|
||||
|
||||
export function quotaWindowBarClass(window: AccountQuotaWindow) {
|
||||
if (window.usedPercent === null)
|
||||
return 'bg-(--cp-default-border-hover)'
|
||||
if (window.usedPercent >= 95)
|
||||
return 'bg-(--cp-danger)'
|
||||
if (window.usedPercent >= 80)
|
||||
return 'bg-(--cp-warning)'
|
||||
return 'bg-(--cp-success)'
|
||||
}
|
||||
|
||||
export function quotaWindowPercentTextClass(window: AccountQuotaWindow) {
|
||||
if (window.usedPercent === null)
|
||||
return 'text-(--cp-text-muted)'
|
||||
if (window.usedPercent >= 95)
|
||||
return 'text-(--cp-danger-text)'
|
||||
if (window.usedPercent >= 80)
|
||||
return 'text-(--cp-warning-text)'
|
||||
return 'text-(--cp-success-text)'
|
||||
}
|
||||
|
||||
export function quotaWindowLocalUsageDisplay(window: AccountQuotaWindow) {
|
||||
return window.localUsage?.totalTokensDisplay || '-'
|
||||
}
|
||||
|
||||
export function shouldShowQuotaWindowLocalUsage(window: AccountQuotaWindow) {
|
||||
return (window.localUsage?.totalTokens ?? 0) > 0
|
||||
}
|
||||
|
||||
function groupOrder(window: AccountQuotaWindow, order: Map<string, number>) {
|
||||
return order.get(window.group) ?? order.size
|
||||
}
|
||||
@@ -49,11 +49,19 @@ const label = formField('label')
|
||||
>
|
||||
<BaseForm>
|
||||
<BaseFormItem label="名称" required>
|
||||
<BaseInput v-model="name" placeholder="例如:生产环境、测试账号..." />
|
||||
<BaseInput
|
||||
v-model="name"
|
||||
aria-label="名称"
|
||||
placeholder="例如:生产环境、测试账号..."
|
||||
/>
|
||||
</BaseFormItem>
|
||||
|
||||
<BaseFormItem label="标签(可选)">
|
||||
<BaseInput v-model="label" placeholder="备注信息..." />
|
||||
<BaseInput
|
||||
v-model="label"
|
||||
aria-label="标签(可选)"
|
||||
placeholder="备注信息..."
|
||||
/>
|
||||
</BaseFormItem>
|
||||
</BaseForm>
|
||||
|
||||
@@ -89,9 +97,9 @@ const label = formField('label')
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-[13px] font-medium text-(--cp-text-secondary) mb-2">
|
||||
<p class="mb-2 text-[13px] font-medium text-(--cp-text-secondary)">
|
||||
API Key
|
||||
</label>
|
||||
</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<code
|
||||
class="flex-1 px-3 py-2.5 rounded-(--cp-input-radius-base) bg-(--cp-bg-subtle) text-[13px] font-mono text-(--cp-text-primary) break-all"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { dashboardSnapshotView } from '../presenter'
|
||||
import type { dashboardSnapshotView } from '../composables/presenter'
|
||||
import { CircleCheck, RefreshCw, ShieldAlert, TriangleAlert } from '@lucide/vue'
|
||||
import { clamp } from 'es-toolkit'
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import type { EChartsOption } from 'echarts'
|
||||
import type { MetricCardView, MetricTone } from '../presenter'
|
||||
import type { MetricCardView, MetricTone } from '../composables/presenter'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import BaseCard from '@/components/base/BaseCard.vue'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { dashboardTrendView, normalizeDashboardTrendKind } from '../presenter'
|
||||
import type { dashboardTrendView, normalizeDashboardTrendKind } from '../composables/presenter'
|
||||
|
||||
import { toRef } from 'vue'
|
||||
import BaseCard from '@/components/base/BaseCard.vue'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { dashboardSnapshotView } from '../presenter'
|
||||
import type { dashboardSnapshotView } from '../composables/presenter'
|
||||
|
||||
import { Minimize2 } from '@lucide/vue'
|
||||
import BaseCard from '@/components/base/BaseCard.vue'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { dashboardSnapshotView } from '../presenter'
|
||||
import type { dashboardSnapshotView } from '../composables/presenter'
|
||||
import { Box, CheckCircle2, Monitor, RefreshCw, Terminal, TriangleAlert } from '@lucide/vue'
|
||||
|
||||
import { computed } from 'vue'
|
||||
|
||||
+5
-4
@@ -122,15 +122,16 @@ export function dashboardTrendView(trend: DashboardTrend | null) {
|
||||
return { points, summary: usageTrendSummary(points) }
|
||||
}
|
||||
|
||||
return {
|
||||
points: trend.points,
|
||||
summary: trend.summary.map(item => ({
|
||||
const summary = []
|
||||
for (const item of trend.summary) {
|
||||
summary.push({
|
||||
label: item.label,
|
||||
value: trend.kind === 'errors' && item.ratio !== null ? item.ratio : item.value,
|
||||
tone: trendSummaryTone(item.label),
|
||||
colorVar: trendSummaryColorVar(trend.kind, item.label),
|
||||
})),
|
||||
})
|
||||
}
|
||||
return { points: trend.points, summary }
|
||||
}
|
||||
|
||||
export function normalizeDashboardTrendKind(kind: string): DashboardTrendKind {
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
dashboardSnapshotView,
|
||||
dashboardTrendView,
|
||||
normalizeDashboardTrendKind,
|
||||
} from '../presenter'
|
||||
} from './presenter'
|
||||
|
||||
export function useDashboard() {
|
||||
const activeTrendKind = shallowRef(normalizeDashboardTrendKind('usage'))
|
||||
@@ -108,7 +108,7 @@ export function useDashboard() {
|
||||
|
||||
function isCurrentTrendRequest(
|
||||
requestId: number,
|
||||
kind: Awaited<ReturnType<typeof getDashboardTrend>>['kind'],
|
||||
kind: ReturnType<typeof normalizeDashboardTrendKind>,
|
||||
) {
|
||||
return requestId === trendRequestId && activeTrendKind.value === kind
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { BarSeriesOption, EChartsOption, LineSeriesOption } from 'echarts'
|
||||
import type { Ref } from 'vue'
|
||||
import type { dashboardTrendView, normalizeDashboardTrendKind } from '../presenter'
|
||||
import type { dashboardTrendView, normalizeDashboardTrendKind } from './presenter'
|
||||
import { usePreferredReducedMotion } from '@vueuse/core'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed, shallowRef, watch } from 'vue'
|
||||
@@ -46,8 +46,8 @@ const tabs = [
|
||||
]
|
||||
|
||||
export function useRequestTrendChart(options: {
|
||||
points: Readonly<Ref<TrendView['points']>>
|
||||
summary: Readonly<Ref<TrendView['summary']>>
|
||||
points: Readonly<Ref<TrendPoint[]>>
|
||||
summary: Readonly<Ref<TrendSummaryItem[]>>
|
||||
activeKind: Ref<TrendKind>
|
||||
onTrendChange: (kind: TrendKind) => void
|
||||
}) {
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { dashboardTrendView, formatDashboardCompactNumber } from './presenter'
|
||||
|
||||
describe('dashboard presenter', () => {
|
||||
it('aggregates adjacent usage buckets without over-counting cached input', () => {
|
||||
const view = dashboardTrendView({
|
||||
kind: 'usage',
|
||||
points: [point({ inputTokensValue: 10, cachedTokensValue: 8 }), point({ cachedTokensValue: 8 })],
|
||||
summary: [],
|
||||
})
|
||||
|
||||
expect(view.points).toHaveLength(1)
|
||||
expect(view.points[0]).toMatchObject({
|
||||
inputTokensValue: 10,
|
||||
cachedTokensValue: 10,
|
||||
uncachedInputTokensValue: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('formats large dashboard values compactly', () => {
|
||||
expect(formatDashboardCompactNumber(1_250)).toBe('1.25K')
|
||||
expect(formatDashboardCompactNumber(-1)).toBe('0')
|
||||
})
|
||||
})
|
||||
|
||||
function point(overrides: Partial<ReturnType<typeof pointBase>> = {}) {
|
||||
return { ...pointBase(), ...overrides }
|
||||
}
|
||||
|
||||
function pointBase() {
|
||||
return {
|
||||
time: '12:00',
|
||||
requests: '1',
|
||||
requestsValue: 1,
|
||||
inputTokens: '0',
|
||||
inputTokensValue: 0,
|
||||
outputTokens: '0',
|
||||
outputTokensValue: 0,
|
||||
cachedTokens: '0',
|
||||
cachedTokensValue: 0,
|
||||
cacheHitRateValue: 0,
|
||||
tokensValue: 0,
|
||||
errors: '0',
|
||||
errorsValue: 0,
|
||||
latency: '-',
|
||||
latencyValue: null,
|
||||
maxLatency: '-',
|
||||
maxLatencyValue: null,
|
||||
minLatency: '-',
|
||||
minLatencyValue: null,
|
||||
successRate: '100%',
|
||||
successRateValue: 100,
|
||||
}
|
||||
}
|
||||
@@ -106,19 +106,27 @@ function togglePasswordVisible(): void {
|
||||
<p>{{ props.error }}</p>
|
||||
</div>
|
||||
|
||||
<label class="grid min-w-0 gap-2">
|
||||
<div class="grid min-w-0 gap-2">
|
||||
<span class="text-[13px] leading-[1.1] font-bold text-(--login-label)">管理员账号</span>
|
||||
<BaseInput v-model="username" placeholder="admin@example.com" autocomplete="username">
|
||||
<BaseInput
|
||||
v-model="username"
|
||||
name="username"
|
||||
aria-label="管理员账号"
|
||||
placeholder="admin@example.com"
|
||||
autocomplete="username"
|
||||
>
|
||||
<template #prefix>
|
||||
<Mail :size="17" />
|
||||
</template>
|
||||
</BaseInput>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="grid min-w-0 gap-2">
|
||||
<div class="grid min-w-0 gap-2">
|
||||
<span class="text-[13px] leading-[1.1] font-bold text-(--login-label)">访问密钥</span>
|
||||
<BaseInput
|
||||
v-model="password"
|
||||
name="password"
|
||||
aria-label="访问密钥"
|
||||
placeholder="输入会话密钥"
|
||||
:type="passwordType"
|
||||
autocomplete="current-password"
|
||||
@@ -141,7 +149,7 @@ function togglePasswordVisible(): void {
|
||||
</BaseButton>
|
||||
</template>
|
||||
</BaseInput>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 mb-2">
|
||||
<BaseButton
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { rotationOptions } from '../options'
|
||||
import type { rotationOptions } from '../constants'
|
||||
import BaseCard from '@/components/base/BaseCard.vue'
|
||||
|
||||
type RotationOption = (typeof rotationOptions)[number]
|
||||
|
||||
@@ -21,32 +21,60 @@ const requestIntervalMs = defineModel<string>('requestIntervalMs', { required: t
|
||||
body-class="px-5 py-5"
|
||||
>
|
||||
<BaseForm :columns="2" class="max-w-6xl">
|
||||
<BaseFormItem label="单账号最大并发" description="限制单个账号同一时间可承载的请求数">
|
||||
<BaseInput v-model="maxConcurrentPerAccount" type="number">
|
||||
<BaseFormItem
|
||||
label="单账号最大并发"
|
||||
description="限制单个账号同一时间可承载的请求数"
|
||||
>
|
||||
<BaseInput
|
||||
v-model="maxConcurrentPerAccount"
|
||||
aria-label="单账号最大并发"
|
||||
type="number"
|
||||
>
|
||||
<template #prefix>
|
||||
<Gauge class="size-4" />
|
||||
</template>
|
||||
</BaseInput>
|
||||
</BaseFormItem>
|
||||
|
||||
<BaseFormItem label="提前刷新秒数" description="Token 过期前多少秒触发刷新">
|
||||
<BaseInput v-model="refreshMarginSeconds" type="number">
|
||||
<BaseFormItem
|
||||
label="提前刷新秒数"
|
||||
description="Token 过期前多少秒触发刷新"
|
||||
>
|
||||
<BaseInput
|
||||
v-model="refreshMarginSeconds"
|
||||
aria-label="提前刷新秒数"
|
||||
type="number"
|
||||
>
|
||||
<template #prefix>
|
||||
<Timer class="size-4" />
|
||||
</template>
|
||||
</BaseInput>
|
||||
</BaseFormItem>
|
||||
|
||||
<BaseFormItem label="刷新并发数" description="同时刷新 Token 的最大请求数,减小可避免限流">
|
||||
<BaseInput v-model="refreshConcurrency" type="number">
|
||||
<BaseFormItem
|
||||
label="刷新并发数"
|
||||
description="同时刷新 Token 的最大请求数,减小可避免限流"
|
||||
>
|
||||
<BaseInput
|
||||
v-model="refreshConcurrency"
|
||||
aria-label="刷新并发数"
|
||||
type="number"
|
||||
>
|
||||
<template #prefix>
|
||||
<Zap class="size-4" />
|
||||
</template>
|
||||
</BaseInput>
|
||||
</BaseFormItem>
|
||||
|
||||
<BaseFormItem label="请求间隔 ms" description="控制同一账号两次调度之间的最小等待时间">
|
||||
<BaseInput v-model="requestIntervalMs" type="number">
|
||||
<BaseFormItem
|
||||
label="请求间隔 ms"
|
||||
description="控制同一账号两次调度之间的最小等待时间"
|
||||
>
|
||||
<BaseInput
|
||||
v-model="requestIntervalMs"
|
||||
aria-label="请求间隔 ms"
|
||||
type="number"
|
||||
>
|
||||
<template #prefix>
|
||||
<Timer class="size-4" />
|
||||
</template>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { rotationOptions } from '../options'
|
||||
import type { rotationOptions } from '../constants'
|
||||
import { sortBy } from 'es-toolkit'
|
||||
|
||||
import { computed, onMounted, reactive, ref, shallowRef } from 'vue'
|
||||
|
||||
@@ -11,7 +11,7 @@ import RotationStrategyCard from './components/RotationStrategyCard.vue'
|
||||
import RuntimeSettingsCard from './components/RuntimeSettingsCard.vue'
|
||||
import { useAdminApiKey } from './composables/useAdminApiKey'
|
||||
import { useSettingsForm } from './composables/useSettingsForm'
|
||||
import { rotationOptions } from './options'
|
||||
import { rotationOptions } from './constants'
|
||||
|
||||
const {
|
||||
loading,
|
||||
|
||||
@@ -89,7 +89,9 @@ function showDetail(record: Awaited<ReturnType<typeof getOpsErrors>>['items'][nu
|
||||
@page-size-change="handlePageSizeChange"
|
||||
>
|
||||
<template #statusCode="{ row }">
|
||||
<UsageStatusCodeBadge :status-code="row.statusCode" />
|
||||
<UsageStatusCodeBadge
|
||||
:status-code="typeof row.statusCode === 'number' ? row.statusCode : null"
|
||||
/>
|
||||
</template>
|
||||
<template #failureClass="{ row }">
|
||||
<span class="font-mono text-[12px] font-[680] text-(--cp-danger-text)">
|
||||
|
||||
@@ -39,7 +39,7 @@ const props = withDefaults(
|
||||
|
||||
const activeView = shallowRef('cost')
|
||||
const { palette } = useUsageChartPalette()
|
||||
const points = computed(() => props.cost.points)
|
||||
const points = computed<any[]>(() => props.cost.points)
|
||||
|
||||
const viewOptions = [
|
||||
{ label: '费用', value: 'cost' },
|
||||
|
||||
@@ -36,7 +36,7 @@ const props = withDefaults(
|
||||
use([BarChart])
|
||||
|
||||
const { palette } = useUsageChartPalette()
|
||||
const points = computed(() => props.health.points)
|
||||
const points = computed<HealthPoint[]>(() => props.health.points)
|
||||
|
||||
const hasData = computed(
|
||||
() => !props.loading && points.value.some(point => requestCount(point) > 0),
|
||||
|
||||
@@ -33,7 +33,7 @@ const props = withDefaults(
|
||||
|
||||
const activeView = shallowRef('total')
|
||||
const { palette } = useUsageChartPalette()
|
||||
const performancePoints = computed(() => props.performance.points)
|
||||
const performancePoints = computed<PerformancePoint[]>(() => props.performance.points)
|
||||
|
||||
const viewOptions = [
|
||||
{ label: '总耗时', value: 'total' },
|
||||
|
||||
Reference in New Issue
Block a user