Compare commits

..

28 Commits

Author SHA1 Message Date
john 363f9169ba feat(billing): add metering formula admin tab
Expose margin multiplier, FX rate, and cost-mode settings under 计费中心 so operators can adjust DeepSeek billing without env edits.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 15:29:16 +08:00
john d0183cb636 fix(admin): persist image quota by setting remaining directly
Use PUT setImageQuota so admins can lower remaining below the stored plan
limit; grant-only bonus updates silently no-op when bonus is already zero.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 16:22:22 +08:00
john eca1aa635e fix(admin): set user image quota by total instead of delta
Operators expect direct total capacity like space quota; the delta-based
grant UI caused wrong results when entering a target amount on production.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 16:07:49 +08:00
john f8317e8312 feat(billing): show user display name in ledger records
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 14:18:17 +08:00
john a4d46f2b1e feat(admin): add image quota management UI on memind_adm 5174
Add image-quota admin pages and API wiring for plan defaults, ledger, and per-user
grants, plus local verify scripts and AGENTS.md note that this repo is the sole
admin UI surface.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 14:58:38 +08:00
john 4c33f210da fix(memory-v2): align Runtime Control section enabled badge with active switches.
Runtime control has no top-level enabled field; derive section status from agent resolve, injection mode, and lifecycle flags so the admin page matches saved production config.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 21:37:02 +08:00
john 1af5b1dd82 feat(wechat): add admin UI for WeChat LLM intent router toggles.
Expose memindadm controls for the service-account-only intent refinement layer so operators can enable, shadow, and canary the router without touching H5 chatIntentRouter settings.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 21:16:35 +08:00
john 9933bfb89c merge: fix billing usage summary and user balance display 2026-07-31 17:30:27 +08:00
john aca1e58f53 fix(billing): show user balance and correct all-records summary scope
When the usage overview has no date filter, show only all-time totals instead
of a misleading 30-day range block; surface current balance in user analysis.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 17:30:14 +08:00
john 2550b3b323 feat(billing): add usage analytics charts and summary totals
Add daily usage trend charts with multi-metric toggles, overview vs user
analysis views, date-range filtering, and usage summary API for interval
and all-time totals.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 11:28:47 +08:00
john 2a1c221bb3 feat(billing): show user display name in usage records
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 09:51:38 +08:00
john 65a6d7254b merge: gate memind-lib DeepSeek catalog on deepseek-v4 models 2026-07-26 10:13:45 +08:00
john 16b1a90edf fix(release): gate memind-lib DeepSeek catalog on deepseek-v4 models
Refuse memindadm production releases when bundled llm-providers.mjs still
carries the legacy deepseek-chat catalog instead of deepseek-v4-pro/flash.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-26 10:13:34 +08:00
john afc667a9ce merge: 合入任务编排管理页
将 codex/orchestrator-shadow-ui 的 Orchestrator 控制台与路由测试合入主线。
2026-07-25 10:10:14 +08:00
john 10e24be243 test: cover orchestrator admin boundary 2026-07-25 07:20:25 +08:00
john 2596c8f2c6 feat: add orchestrator controls to memindadm 2026-07-25 07:12:53 +08:00
john dd3fed5b14 feat: add Rybbit admin SSO entry 2026-07-24 17:12:31 +08:00
tkmind b009f31aae merge: production-ready Deep Search admin
Merge the verified MindSearch admin configuration and hardened shared-source release gates.
2026-07-24 02:18:48 +00:00
john 4d7bcbe948 fix: harden admin production source gates 2026-07-24 09:53:06 +08:00
john 1b5bbdf467 fix: expose new built-in search services 2026-07-23 22:51:44 +08:00
john 6977f9fc24 feat: select deep search llm in admin 2026-07-23 22:46:14 +08:00
john ce8247743e feat: register local deep search service 2026-07-23 22:27:11 +08:00
john 04859defeb feat: manage pluggable search services 2026-07-23 21:38:41 +08:00
john bacc31c83a Merge branch 'release/episodic-memory-admin-20260722-r3' 2026-07-23 18:23:12 +08:00
john 693fc8a712 Merge remote-tracking branch 'origin/main' 2026-07-23 18:23:09 +08:00
john 00a4855715 fix: wire admin recharge WeChat notifications 2026-07-23 18:14:10 +08:00
tkmind 4f708d10bd Merge pull request 'fix: 等待后台服务真正就绪' (#3) from codex/fix-admin-startup-readiness into main 2026-07-22 05:22:37 +00:00
john 790c5794e9 feat: add image_make controls to admin 2026-07-19 21:28:00 +08:00
33 changed files with 5199 additions and 113 deletions
-1
View File
@@ -1 +0,0 @@
26747
-1
View File
@@ -1 +0,0 @@
25645
+5
View File
@@ -42,5 +42,10 @@ VITE_MAIN_APP_URL=https://h5.tkmind.cn
MEMIND_UMAMI_SSO_SECRET=replace-with-the-same-random-secret-used-by-umami
UMAMI_SSO_USERNAME=admin
# Rybbit 仅允许从 MemindAdm 单点登录进入(必须与 105 Rybbit 一致)
MEMIND_RYBBIT_SSO_SECRET=replace-with-the-same-random-secret-used-by-rybbit
RYBBIT_SSO_EMAIL=admin@tkmind.cn
RYBBIT_URL=https://rybbit.tkmind.cn
# Plaza 帖子预览链接
# VITE_PLAZA_BASE=https://plaza.tkmind.cn
+1
View File
@@ -8,4 +8,5 @@ dist-ssr/
memind-lib/
.vite/
*.log
*.pid
logs/
+13
View File
@@ -19,3 +19,16 @@ bash scripts/check-release-ready.sh
- `memind_adm` 可以独立开发,但共享用户、权限、策略、技能、计费体系必须继续复用 `Memind` 主实现。
- 发版须 Git commit,禁止本机直 `rsync` 到 `103/105`。
- 共享用户、计费、空间额度、策略同步相关改动必须保留业务验收记录。
## 必读:本仓库是唯一合法的管理后台 UI(5174)
**所有平台管理后台的前端功能只能在本仓库(memind_adm)开发,本地端口 5174,生产 gadm。禁止在 Memind 仓库的 `ops/`(约 3002)新增任何管理页面、导航或 API 客户端。**
| 组件 | 端口 | 职责 |
|------|------|------|
| **memind_adm 前端(本仓库 `src/`)** | **5174** | 管理后台 UI:用户、计费、图片额度、策略、模型中心等 |
| memind_adm API(`server/`) | 8085 | 挂载 `/admin-api/*`,复用 Memind 共享模块 |
| Memind `ops/` | ~3002 | Plaza 运营 + 遗留 admin;**只读维护,禁止扩展** |
| Memind 后端 | 8081 / 8082 | 业务逻辑与 Portal;UI 不在此仓库 |
新增管理功能时:在本仓库添加 `src/admin/pages/*`、更新 `AdminNav.tsx` 与 `App.tsx`;若需新 API,在 `server/app.mjs` 挂载并复用 Memind 模块。Memind 侧仅实现共享业务,不在 `ops/` 做 UI。
+400 -2
View File
@@ -20,6 +20,7 @@
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.13.1",
"recharts": "^3.10.1",
"redis": "^4.7.1",
"sharp": "0.35.2",
"undici": "^6.26.0"
@@ -1711,6 +1712,32 @@
"@redis/client": "^1.0.0"
}
},
"node_modules/@reduxjs/toolkit": {
"version": "2.12.0",
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.12.0.tgz",
"integrity": "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw==",
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"@standard-schema/utils": "^0.3.0",
"immer": "^11.0.0",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"reselect": "^5.1.0"
},
"peerDependencies": {
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
},
"react-redux": {
"optional": true
}
}
},
"node_modules/@resvg/resvg-js": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js/-/resvg-js-2.6.2.tgz",
@@ -2295,6 +2322,18 @@
"win32"
]
},
"node_modules/@standard-schema/spec": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
@@ -2350,6 +2389,69 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
"license": "MIT"
},
"node_modules/@types/d3-color": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
"license": "MIT"
},
"node_modules/@types/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
"license": "MIT"
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@types/d3-path": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
},
"node_modules/@types/d3-shape": {
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
"integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "*"
}
},
"node_modules/@types/d3-time": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
"license": "MIT"
},
"node_modules/@types/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -2379,7 +2481,7 @@
"version": "19.2.17",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"dev": true,
"devOptional": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -2395,6 +2497,12 @@
"@types/react": "^19.2.0"
}
},
"node_modules/@types/use-sync-external-store": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
"license": "MIT"
},
"node_modules/@vitejs/plugin-react": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
@@ -2645,6 +2753,15 @@
"wrap-ansi": "^6.2.0"
}
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/cluster-key-slot": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
@@ -2723,9 +2840,130 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
"integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-ease": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
"integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-format": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",
"integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-path": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
"license": "ISC",
"dependencies": {
"d3-array": "2.10.0 - 3",
"d3-format": "1 - 3",
"d3-interpolate": "1.2.0 - 3",
"d3-time": "2.1.1 - 3",
"d3-time-format": "2 - 4"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
"license": "ISC",
"dependencies": {
"d3-path": "^3.1.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
"license": "ISC",
"dependencies": {
"d3-array": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time-format": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
"license": "ISC",
"dependencies": {
"d3-time": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-timer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
"integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -2752,6 +2990,12 @@
"node": ">=0.10.0"
}
},
"node_modules/decimal.js-light": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
"license": "MIT"
},
"node_modules/denque": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
@@ -2867,6 +3111,17 @@
"node": ">= 0.4"
}
},
"node_modules/es-toolkit": {
"version": "1.50.0",
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.50.0.tgz",
"integrity": "sha512-OyZKhUVvEep9ITEiwHn8GKnMRQIVqoSIX7WnRbkWgJkllCujilqP2rD0u979tkl8wqyc8ICwlc1UBVv/Sl1G6w==",
"license": "MIT",
"workspaces": [
"docs",
"benchmarks",
"tests/types"
]
},
"node_modules/esbuild": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
@@ -3321,12 +3576,31 @@
"node": ">=0.10.0"
}
},
"node_modules/immer": {
"version": "11.1.15",
"resolved": "https://registry.npmjs.org/immer/-/immer-11.1.15.tgz",
"integrity": "sha512-VrNANlmnWQnh5COXIIOQXM9oOJw7naGKlBT74ZOOR6lpVXc3gFEu9FJLDFcpCJ2j+NWr8TIwtWD//T6ZX6TKiQ==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/internmap": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@@ -4023,6 +4297,36 @@
"react": "^19.2.7"
}
},
"node_modules/react-is": {
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.8.tgz",
"integrity": "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ==",
"license": "MIT",
"peer": true
},
"node_modules/react-redux": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz",
"integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",
"license": "MIT",
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
},
"peerDependencies": {
"@types/react": "^18.2.25 || ^19",
"react": "^18.0 || ^19",
"redux": "^5.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"redux": {
"optional": true
}
}
},
"node_modules/react-refresh": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
@@ -4071,6 +4375,42 @@
"react-dom": ">=18"
}
},
"node_modules/recharts": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.10.1.tgz",
"integrity": "sha512-QXFrvt6IVcw7eeZCoyXTwkIJAX3Dv1nyVhMicXJ47GsGDDpcN8z6o644DibE9XjpBTThtsomLKnTV6lc+cVFUA==",
"license": "MIT",
"workspaces": [
"www"
],
"dependencies": {
"@reduxjs/toolkit": "^1.9.0 || 2.x.x",
"clsx": "^2.1.1",
"decimal.js-light": "^2.5.1",
"es-toolkit": "^1.39.3",
"eventemitter3": "^5.0.1",
"immer": "^11.1.8",
"react-redux": "8.x.x || 9.x.x",
"reselect": "5.2.0",
"tiny-invariant": "^1.3.3",
"use-sync-external-store": "^1.2.2",
"victory-vendor": "^37.0.2"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/recharts/node_modules/eventemitter3": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
"node_modules/redis": {
"version": "4.7.1",
"resolved": "https://registry.npmjs.org/redis/-/redis-4.7.1.tgz",
@@ -4088,6 +4428,21 @@
"@redis/time-series": "1.1.0"
}
},
"node_modules/redux": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT"
},
"node_modules/redux-thunk": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
"license": "MIT",
"peerDependencies": {
"redux": "^5.0.0"
}
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -4109,6 +4464,12 @@
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
"license": "MIT"
},
"node_modules/reselect": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",
"integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==",
"license": "MIT"
},
"node_modules/rollup": {
"version": "4.62.0",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.0.tgz",
@@ -4465,6 +4826,12 @@
"node": ">=8"
}
},
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -4592,6 +4959,15 @@
"browserslist": ">= 4.21.0"
}
},
"node_modules/use-sync-external-store": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -4610,6 +4986,28 @@
"node": ">= 0.8"
}
},
"node_modules/victory-vendor": {
"version": "37.3.6",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
"integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",
"license": "MIT AND ISC",
"dependencies": {
"@types/d3-array": "^3.0.3",
"@types/d3-ease": "^3.0.0",
"@types/d3-interpolate": "^3.0.1",
"@types/d3-scale": "^4.0.2",
"@types/d3-shape": "^3.1.0",
"@types/d3-time": "^3.0.0",
"@types/d3-timer": "^3.0.0",
"d3-array": "^3.1.6",
"d3-ease": "^3.0.1",
"d3-interpolate": "^3.0.1",
"d3-scale": "^4.0.2",
"d3-shape": "^3.1.0",
"d3-time": "^3.0.0",
"d3-timer": "^3.0.1"
}
},
"node_modules/vite": {
"version": "6.4.3",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
+2
View File
@@ -12,6 +12,7 @@
"local_restart": "bash scripts/local_restart.sh",
"pro_restart": "bash scripts/pro_restart.sh",
"build": "vite build",
"test:orchestrator": "node --test server/orchestrator-routes.test.mjs",
"preview": "node scripts/preview.mjs",
"dev:preview": "vite preview"
},
@@ -28,6 +29,7 @@
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.13.1",
"recharts": "^3.10.1",
"redis": "^4.7.1",
"sharp": "0.35.2",
"undici": "^6.26.0"
+46 -3
View File
@@ -88,12 +88,24 @@ need_cmd shasum
need_cmd node
if [[ -x "${ROOT}/scripts/check-release-ready.sh" ]]; then
bash "${ROOT}/scripts/check-release-ready.sh"
ALLOW_MAIN_RELEASE=1 bash "${ROOT}/scripts/check-release-ready.sh"
else
echo "缺少发布前闸门: ${ROOT}/scripts/check-release-ready.sh" >&2
exit 1
fi
ROOT_GIT_BRANCH="$(git -C "${ROOT}" branch --show-current)"
ROOT_GIT_HEAD="$(git -C "${ROOT}" rev-parse HEAD)"
ROOT_ORIGIN_HEAD="$(git -C "${ROOT}" rev-parse origin/main)"
[[ "${ROOT_GIT_BRANCH}" == "main" ]] || {
echo "memindadm 生产发布必须从 main 执行,当前分支: ${ROOT_GIT_BRANCH:-detached}" >&2
exit 1
}
[[ "${ROOT_GIT_HEAD}" == "${ROOT_ORIGIN_HEAD}" ]] || {
echo "memindadm main 必须与 origin/main 完全一致" >&2
exit 1
}
[[ -f "${IGNORE_FILE}" ]] || {
echo "缺少忽略文件: ${IGNORE_FILE}" >&2
exit 1
@@ -127,8 +139,23 @@ say "验证共享模块图像运行依赖"
exit 1
}
MEMIND_GIT_HEAD="$(git -C "${MEMIND_SRC}" rev-parse HEAD 2>/dev/null || echo unknown)"
MEMIND_GIT_BRANCH="$(git -C "${MEMIND_SRC}" branch --show-current 2>/dev/null || echo detached)"
git -C "${MEMIND_SRC}" fetch origin main --quiet
MEMIND_GIT_HEAD="$(git -C "${MEMIND_SRC}" rev-parse HEAD)"
MEMIND_ORIGIN_HEAD="$(git -C "${MEMIND_SRC}" rev-parse origin/main)"
MEMIND_GIT_BRANCH="$(git -C "${MEMIND_SRC}" branch --show-current)"
[[ "${MEMIND_GIT_BRANCH}" == "main" ]] || {
echo "Memind 共享模块必须从 main 打包,当前分支: ${MEMIND_GIT_BRANCH:-detached}" >&2
exit 1
}
[[ "${MEMIND_GIT_HEAD}" == "${MEMIND_ORIGIN_HEAD}" ]] || {
echo "Memind main 必须与 origin/main 完全一致" >&2
exit 1
}
[[ -z "$(git -C "${MEMIND_SRC}" status --porcelain=v1 --untracked-files=all)" ]] || {
echo "Memind 共享模块工作区必须干净" >&2
git -C "${MEMIND_SRC}" status --short --untracked-files=all >&2
exit 1
}
say "打包 Memind 共享模块到 memind-lib"
rm -rf "${MEMIND_LIB}"
@@ -169,6 +196,22 @@ grep -q 'tkmind-excel' "${MEMIND_LIB}/capabilities.mjs" || {
echo "memind-lib 缺少 Excel Analyst runtime 扩展映射" >&2
exit 1
}
[[ -f "${MEMIND_LIB}/llm-providers.mjs" ]] || {
echo "memind-lib 缺少 llm-providers.mjs" >&2
exit 1
}
grep -q "'deepseek-v4-pro'" "${MEMIND_LIB}/llm-providers.mjs" || {
echo "memind-lib/llm-providers.mjs 缺少 deepseek-v4-pro 模型目录,拒绝发布旧 DeepSeek catalog" >&2
exit 1
}
grep -q "'deepseek-v4-flash'" "${MEMIND_LIB}/llm-providers.mjs" || {
echo "memind-lib/llm-providers.mjs 缺少 deepseek-v4-flash 模型目录" >&2
exit 1
}
if grep -q "'deepseek-chat'" "${MEMIND_LIB}/llm-providers.mjs" && ! grep -q "LEGACY_DEEPSEEK_CHAT" "${MEMIND_LIB}/llm-providers.mjs"; then
echo "memind-lib/llm-providers.mjs 仍含 legacy deepseek-chat 且无 LEGACY_DEEPSEEK_CHAT 标记,目录可能未升级" >&2
exit 1
fi
if [[ "${AUTO_YES}" -ne 1 && "${DRY_RUN}" -ne 1 ]]; then
say "发布确认"
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env node
/**
* Local smoke test for image-quota admin API (memind_adm 8085).
* Usage: node scripts/verify-image-quota-local.mjs
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const base = process.env.ADM_DEV_BACKEND ?? 'http://127.0.0.1:8085';
function loadEnvFile(filePath) {
if (!fs.existsSync(filePath)) return;
for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eq = trimmed.indexOf('=');
if (eq <= 0) continue;
const key = trimmed.slice(0, eq).trim();
let value = trimmed.slice(eq + 1).trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
if (!(key in process.env)) process.env[key] = value;
}
}
loadEnvFile(path.join(root, '.env'));
const username = process.env.H5_ADMIN_USERNAME?.trim() || 'admin';
const password = process.env.H5_ADMIN_PASSWORD?.trim() || process.env.ADMIN_PASSWORD?.trim() || '';
async function request(method, urlPath, { body, cookie } = {}) {
const res = await fetch(`${base}${urlPath}`, {
method,
headers: {
...(body ? { 'Content-Type': 'application/json' } : {}),
...(cookie ? { Cookie: cookie } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json = null;
try {
json = text ? JSON.parse(text) : null;
} catch {
json = { raw: text.slice(0, 200) };
}
return { status: res.status, json, setCookie: res.headers.getSetCookie?.() ?? [] };
}
function cookieFromSetCookie(setCookie) {
return setCookie.map((c) => c.split(';')[0]).join('; ');
}
function assertOk(cond, msg) {
if (!cond) throw new Error(msg);
}
async function main() {
console.log(`==> Admin API base: ${base}`);
if (!password) {
console.error('缺少 H5_ADMIN_PASSWORD(请在 memind_adm/.env 配置)');
process.exit(1);
}
const login = await request('POST', '/auth/login', {
body: { username, password },
});
assertOk(login.status === 200, `登录失败 HTTP ${login.status}: ${JSON.stringify(login.json)}`);
const cookie = cookieFromSetCookie(login.setCookie);
assertOk(cookie, '登录未返回 session cookie');
console.log(`✓ 管理员登录 (${username})`);
const config = await request('GET', '/admin-api/image-quota/config', { cookie });
assertOk(config.status === 200, `config HTTP ${config.status}`);
assertOk(Array.isArray(config.json?.plans), 'config.plans 应为数组');
assertOk(config.json.plans.length > 0, 'config.plans 不应为空');
console.log(`✓ GET /admin-api/image-quota/config (${config.json.plans.length} 套餐)`);
const users = await request('GET', '/admin-api/users?page=1&pageSize=5&role=user', { cookie });
assertOk(users.status === 200, `users HTTP ${users.status}`);
const sampleUser = users.json?.users?.[0];
assertOk(sampleUser?.id, '需要至少一个 user 账号做用户级测试');
console.log(`✓ 样本用户: ${sampleUser.username} (${sampleUser.id})`);
const userQuota = await request('GET', `/admin-api/users/${sampleUser.id}/image-quota`, { cookie });
assertOk(userQuota.status === 200, `user image-quota HTTP ${userQuota.status}`);
assertOk(userQuota.json?.quota, '应返回 quota 对象');
console.log(
`✓ GET user image-quota: remaining=${userQuota.json.quota.remaining ?? '∞'} unlimited=${userQuota.json.quota.unlimited}`,
);
const ledger = await request('GET', '/admin-api/image-quota/ledger?page=1&pageSize=5', { cookie });
assertOk(ledger.status === 200, `ledger HTTP ${ledger.status}`);
assertOk(Array.isArray(ledger.json?.entries), 'ledger.entries 应为数组');
console.log(`✓ GET /admin-api/image-quota/ledger (${ledger.json.total} 条)`);
const grant = await request('POST', `/admin-api/users/${sampleUser.id}/image-quota/grant`, {
cookie,
body: { delta: 1, note: 'local-verify-image-quota' },
});
assertOk(grant.status === 200, `grant HTTP ${grant.status}: ${JSON.stringify(grant.json)}`);
assertOk(grant.json?.quota, 'grant 应返回更新后的 quota');
console.log(`✓ POST grant +1 → remaining=${grant.json.quota.remaining ?? '∞'}`);
const revoke = await request('POST', `/admin-api/users/${sampleUser.id}/image-quota/grant`, {
cookie,
body: { delta: -1, note: 'local-verify-image-quota-rollback' },
});
assertOk(revoke.status === 200, `rollback grant HTTP ${revoke.status}`);
console.log('✓ POST grant -1 回滚测试额度');
console.log('\n全部 image-quota Admin API 联调通过。');
}
main().catch((err) => {
console.error('\n联调失败:', err.message);
process.exit(1);
});
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env node
/** Portal smoke: /auth/me subscription includes image quota fields */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const memindRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '../..', 'Memind');
const portalBase = process.env.PORTAL_BASE ?? 'http://127.0.0.1:8081';
function loadEnvFile(filePath) {
if (!fs.existsSync(filePath)) return;
for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eq = trimmed.indexOf('=');
if (eq <= 0) continue;
const key = trimmed.slice(0, eq).trim();
let value = trimmed.slice(eq + 1).trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
if (!(key in process.env)) process.env[key] = value;
}
}
loadEnvFile(path.join(memindRoot, '.env'));
const username = process.env.H5_TEST_USERNAME?.trim() || process.env.H5_ADMIN_USERNAME?.trim() || 'admin';
const password = process.env.H5_TEST_PASSWORD?.trim() || process.env.H5_ADMIN_PASSWORD?.trim() || '';
async function request(method, urlPath, { body, cookie } = {}) {
const res = await fetch(`${portalBase}${urlPath}`, {
method,
headers: {
...(body ? { 'Content-Type': 'application/json' } : {}),
...(cookie ? { Cookie: cookie } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json = null;
try { json = text ? JSON.parse(text) : null; } catch { json = { raw: text.slice(0, 200) }; }
return { status: res.status, json, setCookie: res.headers.getSetCookie?.() ?? [] };
}
function cookieFromSetCookie(setCookie) {
return setCookie.map((c) => c.split(';')[0]).join('; ');
}
async function main() {
console.log(`==> Portal base: ${portalBase}`);
if (!password) {
console.error('缺少登录密码(Memind/.env 中 H5_ADMIN_PASSWORD 或 H5_TEST_PASSWORD)');
process.exit(1);
}
const login = await request('POST', '/auth/login', { body: { username, password } });
if (login.status !== 200) {
console.error(`登录失败 HTTP ${login.status}`);
process.exit(1);
}
const cookie = cookieFromSetCookie(login.setCookie);
console.log(`✓ Portal 登录 (${username})`);
const me = await request('GET', '/auth/me', { cookie });
if (me.status !== 200) {
console.error(`/auth/me HTTP ${me.status}`);
process.exit(1);
}
const sub = me.json?.user?.subscription;
if (!sub) {
console.log('⚠ 当前用户无 active subscription(免费用户可能无订阅记录)');
process.exit(0);
}
const fields = ['periodImagesLimit', 'periodImagesUsed', 'periodImagesBonus'];
for (const f of fields) {
if (!(f in sub)) {
console.error(`subscription 缺少字段: ${f}`);
process.exit(1);
}
}
console.log(
`✓ /auth/me subscription 图片额度: limit=${sub.periodImagesLimit} bonus=${sub.periodImagesBonus ?? 0} used=${sub.periodImagesUsed}`,
);
console.log('\nPortal 用户侧 subscription 字段联调通过。');
}
main().catch((err) => {
console.error('联调失败:', err.message);
process.exit(1);
});
+256 -1
View File
@@ -4,7 +4,7 @@ import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import express from 'express';
import { listUsagePaged, listLedgerPaged } from './pagination.mjs';
import { listUsagePaged, listLedgerPaged, getUsageStats, getUsageSummary } from './pagination.mjs';
const projectRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -100,8 +100,11 @@ export function createAdminApp(services) {
updateMindSpaceConfig,
memoryV2ConfigService,
mindSearchConfigService,
orchestratorConfigService,
orchestratorObservabilityService,
personalMemoryCandidateStore,
skillRuntimeConfigService,
billingConfigService,
wechatScheduleLlmConfigService,
adminSystemTestService,
systemTestAccountService,
@@ -232,6 +235,21 @@ export function createAdminApp(services) {
res.json({ url: `${baseUrl}/auth/memind?ticket=${encoded}.${signature}` });
});
adminApi.get('/analytics/rybbit-sso', requireAdmin, async (_req, res) => {
const sharedSecret = process.env.MEMIND_RYBBIT_SSO_SECRET?.trim();
if (!sharedSecret) return res.status(503).json({ message: '未配置 Rybbit 单点登录密钥' });
const email = process.env.RYBBIT_SSO_EMAIL?.trim().toLowerCase();
if (!email) return res.status(503).json({ message: '未配置 Rybbit 单点登录账号' });
const baseUrl = String(process.env.RYBBIT_URL || 'https://rybbit.tkmind.cn').replace(/\/$/, '');
const encoded = Buffer.from(JSON.stringify({
email,
exp: Math.floor(Date.now() / 1000) + 60,
nonce: crypto.randomUUID(),
})).toString('base64url');
const signature = crypto.createHmac('sha256', sharedSecret).update(encoded).digest('base64url');
res.json({ url: `${baseUrl}/api/auth/memind?ticket=${encoded}.${signature}` });
});
adminApi.get('/users', requireAdmin, async (req, res) => {
const result = await userAuth.listUsers({
page: Number(req.query.page) || 1,
@@ -290,7 +308,29 @@ export function createAdminApp(services) {
res.json({ user: result.user });
});
async function handleUsageStats(req, res) {
try {
const result = await getUsageStats(pool, req.query);
res.json(result);
} catch (err) {
if (err?.code === 'INVALID_TIME_RANGE') {
return res.status(400).json({ message: '无效的时间范围' });
}
throw err;
}
}
adminApi.get('/usage/summary', requireAdmin, async (req, res) => {
const result = await getUsageSummary(pool, req.query);
res.json(result);
});
adminApi.get('/usage/stats', requireAdmin, handleUsageStats);
adminApi.get('/usage', requireAdmin, async (req, res) => {
if (req.query.stats === '1' || req.query.stats === 'true') {
return handleUsageStats(req, res);
}
const result = await listUsagePaged(pool, req.query);
res.json(result);
});
@@ -382,6 +422,14 @@ export function createAdminApp(services) {
res.json(result);
});
adminApi.get('/memory-v2/runtime', requireAdmin, async (_req, res) => {
if (!memoryV2ConfigService?.getRuntimeState) {
return res.status(503).json({ message: 'Memory V2 配置服务未启用' });
}
const result = await memoryV2ConfigService.getRuntimeState();
return res.json(result);
});
adminApi.get('/mindsearch/config', requireAdmin, async (_req, res) => {
if (!mindSearchConfigService?.getAdminConfig) return res.status(503).json({ message: 'MindSearch 配置未启用' });
res.json(await mindSearchConfigService.getAdminConfig());
@@ -401,6 +449,80 @@ export function createAdminApp(services) {
if (!mindSearchConfigService?.getRuntimeState) return res.status(503).json({ message: 'MindSearch 配置未启用' });
res.json(await mindSearchConfigService.getRuntimeState());
});
adminApi.post('/mindsearch/services/:serviceId/test', requireAdmin, async (req, res) => {
if (!mindSearchConfigService?.testService) return res.status(503).json({ message: 'MindSearch 服务测试未启用' });
try {
return res.json(await mindSearchConfigService.testService(req.params.serviceId));
} catch (error) {
if (error?.code === 'SEARCH_SERVICE_NOT_FOUND') return res.status(404).json({ message: error.message });
throw error;
}
});
adminApi.get('/orchestrator/config', requireAdmin, async (_req, res) => {
if (!orchestratorConfigService?.getAdminConfig) {
return res.status(503).json({ message: 'Orchestrator 配置服务未启用' });
}
return res.json(await orchestratorConfigService.getAdminConfig());
});
const updateOrchestratorConfig = async (req, res) => {
if (!orchestratorConfigService?.updateAdminConfig) {
return res.status(503).json({ message: 'Orchestrator 配置服务未启用' });
}
return res.json(await orchestratorConfigService.updateAdminConfig(
req.body?.config ?? req.body ?? {},
{ updatedBy: req.currentUser.id },
));
};
adminApi.put('/orchestrator/config', requireAdmin, updateOrchestratorConfig);
adminApi.patch('/orchestrator/config', requireAdmin, updateOrchestratorConfig);
adminApi.get('/orchestrator/runtime', requireAdmin, async (_req, res) => {
if (!orchestratorConfigService?.getRuntimeState) {
return res.status(503).json({ message: 'Orchestrator 配置服务未启用' });
}
return res.json(await orchestratorConfigService.getRuntimeState({ probe: true }));
});
adminApi.get('/orchestrator/shadow-runs', requireAdmin, async (req, res) => {
if (!orchestratorObservabilityService?.listShadowRuns) {
return res.status(503).json({ message: 'Orchestrator 观测服务未启用' });
}
return res.json(await orchestratorObservabilityService.listShadowRuns({
hours: req.query.hours,
limit: req.query.limit,
status: req.query.status,
}));
});
adminApi.get('/orchestrator/execution-plans', requireAdmin, async (req, res) => {
if (!orchestratorObservabilityService?.listExecutionPlans) {
return res.status(503).json({ message: 'Orchestrator Dry-run 观测服务未启用' });
}
return res.json(await orchestratorObservabilityService.listExecutionPlans({
hours: req.query.hours,
limit: req.query.limit,
selection: req.query.selection,
}));
});
adminApi.get('/orchestrator/canary-readiness', requireAdmin, async (_req, res) => {
if (!orchestratorObservabilityService?.getCanaryReadiness) {
return res.status(503).json({ message: 'Orchestrator 观测服务未启用' });
}
return res.json(await orchestratorObservabilityService.getCanaryReadiness());
});
adminApi.get('/orchestrator/shadow-runs/:runId', requireAdmin, async (req, res) => {
if (!orchestratorObservabilityService?.getShadowRun) {
return res.status(503).json({ message: 'Orchestrator 观测服务未启用' });
}
const result = await orchestratorObservabilityService.getShadowRun(req.params.runId);
if (!result) return res.status(404).json({ message: 'Shadow run 不存在' });
return res.json(result);
});
adminApi.get('/memory-v2/status', requireAdmin, async (_req, res) => {
const portalBaseUrl = `http://127.0.0.1:${process.env.H5_PORT ?? 8081}`;
@@ -507,6 +629,40 @@ export function createAdminApp(services) {
res.json(await skillRuntimeConfigService.getPublicRuntimeConfig());
});
adminApi.get('/billing/config', requireAdmin, async (_req, res) => {
if (!billingConfigService?.getAdminConfig) {
return res.status(503).json({ message: '计费公式配置服务未启用' });
}
return res.json(await billingConfigService.getAdminConfig());
});
const updateBillingConfig = async (req, res) => {
if (!billingConfigService?.updateAdminConfig) {
return res.status(503).json({ message: '计费公式配置服务未启用' });
}
try {
return res.json(await billingConfigService.updateAdminConfig(
req.body?.config ?? req.body ?? {},
{ updatedBy: req.currentUser.id },
));
} catch (error) {
if (error?.code === 'BILLING_CONFIG_ENV_LOCKED') {
return res.status(409).json({ message: error.message, code: error.code });
}
throw error;
}
};
adminApi.put('/billing/config', requireAdmin, updateBillingConfig);
adminApi.patch('/billing/config', requireAdmin, updateBillingConfig);
adminApi.get('/billing/runtime', requireAdmin, async (_req, res) => {
if (!billingConfigService?.getRuntimeState) {
return res.status(503).json({ message: '计费公式配置服务未启用' });
}
return res.json(await billingConfigService.getRuntimeState());
});
adminApi.get('/system-tests/accounts', requireAdmin, async (_req, res) => {
if (!systemTestAccountService) {
return res.status(503).json({ message: '系统测试账号服务未启用' });
@@ -1062,6 +1218,105 @@ export function createAdminApp(services) {
res.json(result);
});
// ── Image generation quota ────────────────────────────────────────────────
adminApi.get('/image-quota/config', requireAdmin, async (_req, res) => {
const catalogService = subscriptionService?._planCatalogService ?? planCatalogService;
if (!catalogService?.listPlans) {
return res.status(503).json({ message: '套餐目录服务未启用' });
}
const plans = await catalogService.listPlans();
res.json({ plans });
});
adminApi.patch('/image-quota/config/:planType', requireAdmin, async (req, res) => {
const catalogService = subscriptionService?._planCatalogService ?? planCatalogService;
if (!catalogService?.upsertPlan) {
return res.status(503).json({ message: '套餐目录服务未启用' });
}
const periodImages = Number(req.body?.periodImages);
if (!Number.isFinite(periodImages) || periodImages < 0) {
return res.status(400).json({ message: 'periodImages 必须是非负整数;0 表示无限' });
}
const current = await catalogService.getPlan(req.params.planType);
if (!current) return res.status(404).json({ message: '套餐不存在' });
const result = await catalogService.upsertPlan(req.params.planType, {
...current,
periodImages: Math.floor(periodImages),
});
if (!result.ok) return res.status(400).json({ message: result.message });
res.json(result);
});
adminApi.get('/users/:userId/image-quota', requireAdmin, async (req, res) => {
if (!subscriptionService?.getImageQuota) {
return res.status(503).json({ message: '图片额度服务未启用' });
}
const quotaResult = await subscriptionService.getImageQuota(req.params.userId);
if (!quotaResult.ok) return res.status(404).json({ message: quotaResult.message });
const ledger = subscriptionService.listImageQuotaLedger
? await subscriptionService.listImageQuotaLedger({
userId: req.params.userId,
page: 1,
pageSize: 20,
})
: { entries: [] };
res.json({
subscription: quotaResult.subscription,
quota: quotaResult.quota,
ledger: ledger.entries,
});
});
adminApi.put('/users/:userId/image-quota', requireAdmin, async (req, res) => {
if (!subscriptionService?.setImageQuota) {
return res.status(503).json({ message: '图片额度服务未启用' });
}
const remaining = req.body?.remaining;
const total = req.body?.total;
const note = String(req.body?.note ?? '').trim();
const result = await subscriptionService.setImageQuota(
req.params.userId,
{
remaining: remaining === undefined || remaining === null ? null : Math.floor(Number(remaining)),
total: total === undefined || total === null ? null : Math.floor(Number(total)),
},
{ operatorId: req.currentUser.id, note },
);
if (!result.ok) return res.status(400).json({ message: result.message });
res.json(result);
});
adminApi.post('/users/:userId/image-quota/grant', requireAdmin, async (req, res) => {
if (!subscriptionService?.grantImageQuota) {
return res.status(503).json({ message: '图片额度服务未启用' });
}
const delta = Number(req.body?.delta);
if (!Number.isFinite(delta) || delta === 0) {
return res.status(400).json({ message: 'delta 必须是非零整数' });
}
const note = String(req.body?.note ?? '').trim();
const result = await subscriptionService.grantImageQuota(
req.params.userId,
Math.floor(delta),
{ operatorId: req.currentUser.id, note },
);
if (!result.ok) return res.status(400).json({ message: result.message });
res.json(result);
});
adminApi.get('/image-quota/ledger', requireAdmin, async (req, res) => {
if (!subscriptionService?.listImageQuotaLedger) {
return res.status(503).json({ message: '图片额度服务未启用' });
}
const result = await subscriptionService.listImageQuotaLedger({
userId: req.query.userId ? String(req.query.userId) : null,
page: req.query.page,
pageSize: req.query.pageSize,
});
res.json(result);
});
app.use('/admin-api', adminApi);
if (services.createOpsApi) {
+111
View File
@@ -0,0 +1,111 @@
import assert from 'node:assert/strict';
import { once } from 'node:events';
import test from 'node:test';
import { createAdminApp } from './app.mjs';
function createServices({ role = 'admin' } = {}) {
let stored = {
useBackendCost: true,
usdCnyRate: 7.2,
marginMultiplier: 1.2,
inputCentsPer1k: 2,
outputCentsPer1k: 6,
minBillCents: 1,
costEstimateFromTokens: true,
costEstimateInputUsdPer1M: 0.27,
costEstimateOutputUsdPer1M: 1.1,
};
return {
services: {
ready: Promise.resolve(),
parseCookies: () => ({ test_session: 'token' }),
USER_COOKIE: 'test_session',
userLoginCookies: () => [],
clearUserSessionCookie: () => {},
resolveCookieDomainForRequest: () => undefined,
userAuth: {
getMe: async () => ({ id: 'admin-id', username: 'admin', role }),
},
billingConfigService: {
getAdminConfig: async () => ({
config: stored,
source: 'env',
updatedAt: null,
updatedBy: null,
formula: '最终扣费 = 上游成本(USD) × 汇率 × 毛利倍数',
}),
updateAdminConfig: async (patch, context) => {
stored = { ...stored, ...(patch.config ?? patch) };
return {
config: stored,
source: 'admin-db',
updatedAt: Date.now(),
updatedBy: context?.updatedBy ?? null,
formula: '最终扣费 = 上游成本(USD) × 汇率 × 毛利倍数',
};
},
getRuntimeState: async () => ({
source: 'admin-db',
config: stored,
compute: stored,
}),
},
},
};
}
async function startApp(options) {
const harness = createServices(options);
const server = createAdminApp(harness.services).listen(0, '127.0.0.1');
await once(server, 'listening');
const address = server.address();
assert.ok(address && typeof address === 'object');
return {
...harness,
request: (path, init = {}) => fetch(`http://127.0.0.1:${address.port}${path}`, {
...init,
headers: {
Cookie: 'test_session=token',
'Content-Type': 'application/json',
...init.headers,
},
}),
async close() {
server.close();
await once(server, 'close');
},
};
}
test('admin can read and update billing formula config', async (t) => {
const app = await startApp();
t.after(() => app.close());
const read = await app.request('/admin-api/billing/config');
assert.equal(read.status, 200);
const body = await read.json();
assert.equal(body.config.marginMultiplier, 1.2);
const update = await app.request('/admin-api/billing/config', {
method: 'PUT',
body: JSON.stringify({
config: {
...body.config,
marginMultiplier: 1.5,
},
}),
});
assert.equal(update.status, 200);
const updated = await update.json();
assert.equal(updated.config.marginMultiplier, 1.5);
assert.equal(updated.source, 'admin-db');
});
test('ordinary users cannot access billing formula config', async (t) => {
const app = await startApp({ role: 'user' });
t.after(() => app.close());
const read = await app.request('/admin-api/billing/config');
assert.equal(read.status, 403);
});
+32
View File
@@ -18,6 +18,7 @@ export async function bootstrapAdminServices() {
const createLlmProviderService = await loadCreateLlmProviderService();
const { createWechatAdminService } = await importMemind('wechat-admin.mjs');
const { createWechatMpService, loadWechatMpConfig } = await importMemind('wechat-mp.mjs');
const { createNotificationDispatcher } = await importMemind('notification-dispatcher.mjs');
const { createPlazaPostService, formatPostRow } = await importMemind('plaza-posts.mjs');
const { createPlazaInteractionService } = await importMemind('plaza-interactions.mjs');
const { createPlazaOpsService } = await importMemind('plaza-ops.mjs');
@@ -30,8 +31,15 @@ export async function bootstrapAdminServices() {
} = await importMemind('mindspace-config.mjs');
const { createMemoryV2AdminConfigService } = await importMemind('memory-v2-admin-config.mjs');
const { createMindSearchConfigService } = await importMemind('mindsearch-config.mjs');
const { createOrchestratorAdminConfigService } = await importMemind(
'services/orchestrator/admin-config.mjs',
);
const { createOrchestratorObservabilityService } = await importMemind(
'services/orchestrator/observability.mjs',
);
const { createPersonalMemoryCandidateStore } = await importMemind('memory-v2-personal-store.mjs');
const { createSkillRuntimeAdminConfigService } = await importMemind('skill-runtime-admin-config.mjs');
const { createBillingAdminConfigService } = await importMemind('billing-admin-config.mjs');
const { createAssetGatewayConfigService } = await importMemind('asset-gateway.mjs');
const { ensureAssetGatewaySchema } = await importMemind('db.mjs');
const { createWechatScheduleLlmConfigService } = await importMemind('wechat-schedule-llm-config.mjs');
@@ -98,11 +106,23 @@ export async function bootstrapAdminServices() {
});
const mindSearchConfigService = createMindSearchConfigService(pool, { env: process.env });
await mindSearchConfigService.ensureSchema();
const orchestratorConfigService = createOrchestratorAdminConfigService(pool, {
env: process.env,
});
await orchestratorConfigService.ensureSchema();
const orchestratorObservabilityService = createOrchestratorObservabilityService({
pool,
configService: orchestratorConfigService,
});
const personalMemoryCandidateStore = createPersonalMemoryCandidateStore(pool);
const skillRuntimeConfigService = createSkillRuntimeAdminConfigService(pool, {
env: process.env,
h5Root,
});
const billingConfigService = createBillingAdminConfigService(pool, {
env: process.env,
});
await billingConfigService.ensureSchema();
const wechatScheduleLlmConfigService = createWechatScheduleLlmConfigService(pool, {
env: process.env,
});
@@ -119,6 +139,14 @@ export async function bootstrapAdminServices() {
throw new Error('admin api does not proxy WeChat chat sessions');
},
});
const notificationDispatcher = createNotificationDispatcher({
sendWechatTextToUser: wechatMpService?.enabled
? (userId, text) => wechatMpService.sendTextToUser(userId, text)
: null,
});
userAuth.setRechargeNotifier(async ({ userId, title, body, dedupeKey }) => {
await notificationDispatcher.sendRechargeSuccess({ userId, title, body, dedupeKey });
});
const wechatAdmin = createWechatAdminService(pool, {
config: wechatMpConfig,
scheduleEnabled: process.env.H5_SCHEDULE_ENABLED === '1',
@@ -136,6 +164,7 @@ export async function bootstrapAdminServices() {
const subscriptionService = createSubscriptionService(pool, {
getPlanAsync: (planType) => planCatalogService.getPlan(planType),
});
subscriptionService._planCatalogService = planCatalogService;
await ensureSystemTestAccountSchema(pool);
const systemTestAccountService = createSystemTestAccountService(pool);
@@ -156,8 +185,11 @@ export async function bootstrapAdminServices() {
updateMindSpaceConfig,
memoryV2ConfigService,
mindSearchConfigService,
orchestratorConfigService,
orchestratorObservabilityService,
personalMemoryCandidateStore,
skillRuntimeConfigService,
billingConfigService,
wechatScheduleLlmConfigService,
adminSystemTestService,
systemTestAccountService,
+6
View File
@@ -106,8 +106,11 @@ ready
updateMindSpaceConfig,
memoryV2ConfigService,
mindSearchConfigService,
orchestratorConfigService,
orchestratorObservabilityService,
personalMemoryCandidateStore,
skillRuntimeConfigService,
billingConfigService,
wechatScheduleLlmConfigService,
adminSystemTestService,
systemTestAccountService,
@@ -132,8 +135,11 @@ ready
updateMindSpaceConfig,
memoryV2ConfigService,
mindSearchConfigService,
orchestratorConfigService,
orchestratorObservabilityService,
personalMemoryCandidateStore,
skillRuntimeConfigService,
billingConfigService,
wechatScheduleLlmConfigService,
adminSystemTestService,
systemTestAccountService,
+176
View File
@@ -0,0 +1,176 @@
import assert from 'node:assert/strict';
import { once } from 'node:events';
import test from 'node:test';
import { createAdminApp } from './app.mjs';
function createServices({ role = 'admin' } = {}) {
const calls = {
update: [],
shadow: [],
plans: [],
detail: [],
};
const configState = {
config: {
mode: 'shadow',
primaryEngine: 'langgraph',
fallbackEngine: 'native',
serviceUrl: 'http://127.0.0.1:8093',
requestTimeoutMs: 5000,
rolloutPercent: 0,
userAllowlist: [],
workflowAllowlist: ['code-run-v1'],
fallbackToNative: true,
requireHealthy: true,
executionEnabled: false,
},
configVersion: 4,
updatedBy: 'admin-user',
updatedAt: 1,
source: 'admin-db',
runtime: {
effective: true,
shadowsLangGraph: true,
executesLangGraph: false,
executionHandoff: { enabled: false },
},
engines: [],
executors: [],
};
return {
calls,
services: {
ready: Promise.resolve(),
parseCookies: () => ({ test_session: 'token' }),
USER_COOKIE: 'test_session',
userLoginCookies: () => [],
clearUserSessionCookie: () => {},
resolveCookieDomainForRequest: () => undefined,
userAuth: {
getMe: async () => ({ id: 'john-id', username: 'john', role }),
},
orchestratorConfigService: {
getAdminConfig: async () => configState,
updateAdminConfig: async (config, context) => {
calls.update.push({ config, context });
return { ...configState, config, updatedBy: context.updatedBy };
},
getRuntimeState: async ({ probe }) => ({
...configState,
serviceHealth: { ok: true, status: 'healthy', probe },
}),
},
orchestratorObservabilityService: {
listShadowRuns: async (query) => {
calls.shadow.push(query);
return { metrics: { observations: 0 }, runs: [] };
},
listExecutionPlans: async (query) => {
calls.plans.push(query);
return { metrics: { decisions: 0 }, plans: [] };
},
getCanaryReadiness: async () => ({
ready: false,
recommendation: 'keep_shadow',
}),
getShadowRun: async (runId) => {
calls.detail.push(runId);
return runId === 'missing' ? null : { native: { runId }, remote: { available: true } };
},
},
},
};
}
async function startApp(options) {
const harness = createServices(options);
const server = createAdminApp(harness.services).listen(0, '127.0.0.1');
await once(server, 'listening');
const address = server.address();
assert.ok(address && typeof address === 'object');
return {
...harness,
request: (path, init = {}) => fetch(`http://127.0.0.1:${address.port}${path}`, {
...init,
headers: {
Cookie: 'test_session=token',
'Content-Type': 'application/json',
...init.headers,
},
}),
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
test('admin can read orchestrator config, runtime and observability endpoints', async (t) => {
const app = await startApp();
t.after(app.close);
const config = await app.request('/admin-api/orchestrator/config');
assert.equal(config.status, 200);
assert.equal((await config.json()).config.mode, 'shadow');
const runtime = await app.request('/admin-api/orchestrator/runtime');
assert.equal(runtime.status, 200);
assert.deepEqual((await runtime.json()).serviceHealth, {
ok: true,
status: 'healthy',
probe: true,
});
const shadow = await app.request(
'/admin-api/orchestrator/shadow-runs?hours=24&limit=50&status=failed',
);
assert.equal(shadow.status, 200);
assert.deepEqual(app.calls.shadow, [{ hours: '24', limit: '50', status: 'failed' }]);
const plans = await app.request(
'/admin-api/orchestrator/execution-plans?hours=168&limit=20&selection=native',
);
assert.equal(plans.status, 200);
assert.deepEqual(app.calls.plans, [{ hours: '168', limit: '20', selection: 'native' }]);
const readiness = await app.request('/admin-api/orchestrator/canary-readiness');
assert.equal(readiness.status, 200);
assert.equal((await readiness.json()).recommendation, 'keep_shadow');
const detail = await app.request('/admin-api/orchestrator/shadow-runs/run-1');
assert.equal(detail.status, 200);
assert.deepEqual(app.calls.detail, ['run-1']);
const missing = await app.request('/admin-api/orchestrator/shadow-runs/missing');
assert.equal(missing.status, 404);
});
test('admin config update records the authenticated administrator', async (t) => {
const app = await startApp();
t.after(app.close);
const response = await app.request('/admin-api/orchestrator/config', {
method: 'PUT',
body: JSON.stringify({ config: { mode: 'off', executionEnabled: false } }),
});
assert.equal(response.status, 200);
assert.deepEqual(app.calls.update, [{
config: { mode: 'off', executionEnabled: false },
context: { updatedBy: 'john-id' },
}]);
});
test('ordinary users cannot access or mutate orchestrator controls', async (t) => {
const app = await startApp({ role: 'user' });
t.after(app.close);
const read = await app.request('/admin-api/orchestrator/config');
assert.equal(read.status, 403);
const update = await app.request('/admin-api/orchestrator/config', {
method: 'PUT',
body: JSON.stringify({ config: { mode: 'active', executionEnabled: true } }),
});
assert.equal(update.status, 403);
assert.equal(app.calls.update.length, 0);
});
+130 -4
View File
@@ -17,21 +17,145 @@ export function paginateArray(items, query, defaultPageSize = 20) {
};
}
const MS_THRESHOLD = 1_000_000_000_000;
function parseUsageTimeFilters(query) {
const startAt = Number(query.startAt);
const endAt = Number(query.endAt);
const hasStart = Number.isFinite(startAt) && startAt > 0;
const hasEnd = Number.isFinite(endAt) && endAt > 0;
if (!hasStart || !hasEnd || startAt > endAt) {
return null;
}
// Frontend sends unix seconds; h5_usage_records.created_at is stored in milliseconds.
const startAtMs = startAt < MS_THRESHOLD ? startAt * 1000 : startAt;
const endAtMs = endAt < MS_THRESHOLD ? endAt * 1000 + 999 : endAt;
return { startAt, endAt, startAtMs, endAtMs };
}
function formatSqlDay(value) {
if (value instanceof Date) {
const y = value.getFullYear();
const m = String(value.getMonth() + 1).padStart(2, '0');
const d = String(value.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
return String(value).slice(0, 10);
}
export async function getUsageTotals(pool, { userId = null, startAtMs = null, endAtMs = null } = {}) {
const params = [];
const clauses = [];
if (userId) {
clauses.push('r.user_id = ?');
params.push(userId);
}
if (startAtMs != null && endAtMs != null) {
clauses.push('r.created_at >= ?', 'r.created_at <= ?');
params.push(startAtMs, endAtMs);
}
const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';
const [[row]] = await pool.query(
`SELECT COUNT(*) AS count,
COALESCE(SUM(r.input_tokens), 0) AS input_tokens,
COALESCE(SUM(r.output_tokens), 0) AS output_tokens,
COALESCE(SUM(r.cost_cents), 0) AS cost_cents
FROM h5_usage_records r
${where}`,
params,
);
return {
count: Number(row.count),
inputTokens: Number(row.input_tokens),
outputTokens: Number(row.output_tokens),
costCents: Number(row.cost_cents),
};
}
export async function getUsageSummary(pool, query) {
const userId = typeof query.userId === 'string' && query.userId ? query.userId : null;
const range = parseUsageTimeFilters(query);
const allTime = await getUsageTotals(pool, { userId });
if (!range) {
return { range: null, allTime };
}
const rangeTotals = await getUsageTotals(pool, {
userId,
startAtMs: range.startAtMs,
endAtMs: range.endAtMs,
});
return {
range: {
...rangeTotals,
startAt: range.startAt,
endAt: range.endAt,
},
allTime,
};
}
export async function getUsageStats(pool, query) {
const userId = typeof query.userId === 'string' && query.userId ? query.userId : null;
const range = parseUsageTimeFilters(query);
if (!range) {
const err = new Error('INVALID_TIME_RANGE');
err.code = 'INVALID_TIME_RANGE';
throw err;
}
const { startAt, endAt, startAtMs, endAtMs } = range;
const params = [startAtMs, endAtMs];
const clauses = ['r.created_at >= ?', 'r.created_at <= ?'];
if (userId) {
clauses.push('r.user_id = ?');
params.push(userId);
}
const where = `WHERE ${clauses.join(' AND ')}`;
const [rows] = await pool.query(
`SELECT DATE(FROM_UNIXTIME(r.created_at / 1000)) AS day,
COUNT(*) AS count,
COALESCE(SUM(r.input_tokens), 0) AS input_tokens,
COALESCE(SUM(r.output_tokens), 0) AS output_tokens,
COALESCE(SUM(r.cost_cents), 0) AS cost_cents
FROM h5_usage_records r
${where}
GROUP BY day
ORDER BY day ASC`,
params,
);
return {
buckets: rows.map((row) => ({
day: formatSqlDay(row.day),
count: Number(row.count),
inputTokens: Number(row.input_tokens),
outputTokens: Number(row.output_tokens),
costCents: Number(row.cost_cents),
})),
startAt,
endAt,
};
}
export async function listUsagePaged(pool, query) {
const { page, pageSize, offset } = parsePageQuery(query, 20);
const userId = typeof query.userId === 'string' && query.userId ? query.userId : null;
const range = parseUsageTimeFilters(query);
const params = [];
let where = '';
const clauses = [];
if (userId) {
where = 'WHERE r.user_id = ?';
clauses.push('r.user_id = ?');
params.push(userId);
}
if (range) {
clauses.push('r.created_at >= ?', 'r.created_at <= ?');
params.push(range.startAtMs, range.endAtMs);
}
const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';
const [[{ total }]] = await pool.query(
`SELECT COUNT(*) AS total FROM h5_usage_records r ${where}`,
params,
);
const [rows] = await pool.query(
`SELECT r.id, r.user_id, u.username, r.agent_session_id, r.request_id,
`SELECT r.id, r.user_id, u.username, u.display_name, r.agent_session_id, r.request_id,
r.input_tokens, r.output_tokens, r.cost_cents, r.balance_after_cents, r.created_at
FROM h5_usage_records r
JOIN h5_users u ON u.id = r.user_id
@@ -45,6 +169,7 @@ export async function listUsagePaged(pool, query) {
id: Number(row.id),
userId: row.user_id,
username: row.username,
displayName: row.display_name,
agentSessionId: row.agent_session_id,
requestId: row.request_id,
inputTokens: Number(row.input_tokens),
@@ -75,7 +200,7 @@ export async function listLedgerPaged(pool, query) {
params,
);
const [rows] = await pool.query(
`SELECT l.id, l.user_id, u.username, l.type, l.amount_cents, l.tokens,
`SELECT l.id, l.user_id, u.username, u.display_name, l.type, l.amount_cents, l.tokens,
l.session_id, l.note, l.created_at
FROM h5_billing_ledger l
JOIN h5_users u ON u.id = l.user_id
@@ -89,6 +214,7 @@ export async function listLedgerPaged(pool, query) {
id: Number(row.id),
userId: row.user_id,
username: row.username,
displayName: row.display_name,
type: row.type,
amountCents: Number(row.amount_cents),
tokens: Number(row.tokens),
+6
View File
@@ -5,6 +5,7 @@ import { AdminLayout } from './admin/AdminLayout';
import { BillingPage } from './admin/pages/BillingPage';
import { CapabilitiesPage } from './admin/pages/CapabilitiesPage';
import { DashboardPage } from './admin/pages/DashboardPage';
import { ImageQuotaPage } from './admin/pages/ImageQuotaPage';
import { PoliciesPage } from './admin/pages/PoliciesPage';
import { MindSpacePage } from './admin/pages/MindSpacePage';
import { MemoryV2Page } from './admin/pages/MemoryV2Page';
@@ -19,6 +20,7 @@ import { AssetGatewayPage } from './admin/pages/AssetGatewayPage';
import { BlockedWordsPage } from './admin/pages/BlockedWordsPage';
import { AnalyticsConfigPage } from './admin/pages/AnalyticsConfigPage';
import { SkillRuntimePage } from './admin/pages/SkillRuntimePage';
import { OrchestratorPage } from './admin/pages/OrchestratorPage';
import { defaultHomePath } from './lib/routes';
import { OpsLayout } from './ops/components/OpsLayout';
import { AnalyticsPage } from './ops/pages/AnalyticsPage';
@@ -118,6 +120,7 @@ function AdminApp({ user, onLogout }: { user: PortalUser; onLogout: () => void }
<Route path="users" element={<UsersPage />} />
<Route path="users/:userId" element={<UserDetailPage />} />
<Route path="billing/*" element={<BillingPage />} />
<Route path="image-quota" element={<ImageQuotaPage />} />
<Route path="capabilities" element={<CapabilitiesPage />} />
<Route path="skills" element={<SkillsPage />} />
<Route path="system-tests" element={<SystemTestsPage />} />
@@ -127,6 +130,7 @@ function AdminApp({ user, onLogout }: { user: PortalUser; onLogout: () => void }
<Route path="memory-v2" element={<MemoryV2Page />} />
<Route path="mindsearch" element={<MindSearchPage />} />
<Route path="skill-runtime" element={<SkillRuntimePage />} />
<Route path="orchestrator" element={<OrchestratorPage />} />
<Route path="providers" element={<ProvidersPage />} />
<Route path="wechat" element={<WechatPage />} />
<Route path="asset-gateway" element={<AssetGatewayPage />} />
@@ -168,6 +172,7 @@ function loginRedirectPath(pathname: string, role: string | undefined) {
if (
pathname.startsWith('/users')
|| pathname.startsWith('/billing')
|| pathname.startsWith('/image-quota')
|| pathname.startsWith('/capabilities')
|| pathname.startsWith('/skills')
|| pathname.startsWith('/system-tests')
@@ -175,6 +180,7 @@ function loginRedirectPath(pathname: string, role: string | undefined) {
|| pathname.startsWith('/mindspace')
|| pathname.startsWith('/memory-v2')
|| pathname.startsWith('/skill-runtime')
|| pathname.startsWith('/orchestrator')
|| pathname.startsWith('/providers')
|| pathname.startsWith('/wechat')
|| pathname.startsWith('/asset-gateway')
+5 -1
View File
@@ -21,7 +21,10 @@ const NAV_SECTIONS: NavSection[] = [
},
{
label: '计费',
items: [{ to: '/billing', label: '计费中心', end: false }],
items: [
{ to: '/billing', label: '计费中心', end: false },
{ to: '/image-quota', label: '图片额度' },
],
},
{
label: '平台配置',
@@ -32,6 +35,7 @@ const NAV_SECTIONS: NavSection[] = [
{ to: '/memory-v2', label: 'Memory V2' },
{ to: '/mindsearch', label: 'MindSearch' },
{ to: '/skill-runtime', label: 'Skill Runtime' },
{ to: '/orchestrator', label: '任务编排' },
{ to: '/system-tests', label: '系统测试验证' },
{ to: '/capabilities', label: '能力' },
{ to: '/skills', label: '技能' },
+28 -7
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState, type FormEvent } from 'react';
import { getMindSpaceAdminConfig, getUmamiSsoUrl, updateMindSpaceAdminConfig } from '../../api/client';
import { getMindSpaceAdminConfig, getRybbitSsoUrl, getUmamiSsoUrl, updateMindSpaceAdminConfig } from '../../api/client';
const initial = {
enabled: false,
@@ -16,7 +16,8 @@ export function AnalyticsConfigPage() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [opening, setOpening] = useState(false);
const [openingUmami, setOpeningUmami] = useState(false);
const [openingRybbit, setOpeningRybbit] = useState(false);
const load = useCallback(async () => {
setLoading(true);
@@ -52,23 +53,43 @@ export function AnalyticsConfigPage() {
};
const openUmami = async () => {
setOpening(true);
setOpeningUmami(true);
setError(null);
try {
window.location.assign(await getUmamiSsoUrl());
} catch (err) {
setError(err instanceof Error ? err.message : '无法打开 Umami');
setOpening(false);
setOpeningUmami(false);
}
};
const openRybbit = async () => {
setOpeningRybbit(true);
setError(null);
try {
window.location.assign(await getRybbitSsoUrl());
} catch (err) {
setError(err instanceof Error ? err.message : '无法打开 Rybbit');
setOpeningRybbit(false);
}
};
return <div className="admin-page">
<div className="admin-page-head"><h2>Analytics 配置</h2><p className="muted">配置本地 Memind 生成页面的 Umami 统计。默认只连接本机 Umami,不涉及生产环境。</p></div>
<div className="admin-page-head"><h2>Analytics 配置</h2><p className="muted">进入统计后台,或配置 Memind 生成页面的 Umami 统计。</p></div>
{error && <p className="banner banner-error">{error}</p>}
{message && <p className="banner banner-info">{message}</p>}
<section className="admin-card">
<h2>本地 Umami</h2>
<div className="admin-actions" style={{ marginBottom: 16 }}><button type="button" className="send-btn" onClick={() => void openUmami()} disabled={opening || loading}>{opening ? '正在进入 Umami...' : '打开 Umami 分析后台'}</button></div>
<h2>Rybbit 行为分析</h2>
<p className="muted">查看页面访问、用户会话、停留时间、点击和会话回放等行为明细。</p>
<div className="admin-actions">
<button type="button" className="send-btn" onClick={() => void openRybbit()} disabled={openingRybbit}>
{openingRybbit ? '正在进入 Rybbit...' : '打开 Rybbit 分析后台'}
</button>
</div>
</section>
<section className="admin-card">
<h2>Umami</h2>
<div className="admin-actions" style={{ marginBottom: 16 }}><button type="button" className="send-btn" onClick={() => void openUmami()} disabled={openingUmami || loading}>{openingUmami ? '正在进入 Umami...' : '打开 Umami 分析后台'}</button></div>
<form className="admin-form" onSubmit={save}>
<label className="admin-form-row"><span>启用页面统计</span><input type="checkbox" checked={config.enabled} disabled={loading || busy} onChange={(e) => setConfig({ ...config, enabled: e.target.checked })} /></label>
<label className="admin-form-row"><span>Website ID</span><input value={config.websiteId} disabled={loading || busy} onChange={(e) => setConfig({ ...config, websiteId: e.target.value })} placeholder="Umami Website ID" required={config.enabled} /></label>
+43 -2
View File
@@ -12,6 +12,7 @@ type PluginDraft = {
provider: string;
llmProviderKeyId: string;
llmModel: string;
purposes: Record<string, boolean>;
};
function draftFromPlugin(plugin: AssetPluginConfig): PluginDraft {
@@ -20,6 +21,7 @@ function draftFromPlugin(plugin: AssetPluginConfig): PluginDraft {
provider: plugin.provider ?? '',
llmProviderKeyId: plugin.llmProviderKeyId ?? '',
llmModel: plugin.llmModel ?? '',
purposes: { ...(plugin.purposes ?? {}) },
};
}
@@ -61,6 +63,16 @@ export function AssetGatewayPage() {
setDrafts((current) => ({ ...current, [pluginId]: { ...current[pluginId], ...patch } }));
};
const updatePurpose = (pluginId: string, purposeId: string, enabled: boolean) => {
setDrafts((current) => ({
...current,
[pluginId]: {
...current[pluginId],
purposes: { ...(current[pluginId]?.purposes ?? {}), [purposeId]: enabled },
},
}));
};
const saveGlobal = async (enabled: boolean) => {
setBusy('global'); setMessage(null); setError(null);
try {
@@ -81,6 +93,7 @@ export function AssetGatewayPage() {
provider: draft.provider || null,
llmProviderKeyId: draft.llmProviderKeyId || null,
llmModel: draft.llmModel || null,
purposes: draft.purposes,
});
setConfig(result.config);
setDrafts(Object.fromEntries(result.config.plugins.map((item) => [item.pluginId, draftFromPlugin(item)])));
@@ -126,11 +139,21 @@ export function AssetGatewayPage() {
</label>
</div>
<div className="asset-plugin-fields">
<label>运行 Provider<select value={draft.provider} onChange={(event) => updateDraft(plugin.pluginId, { provider: event.target.value })} disabled={!draft.enabled}>
<label>运行 Provider<select value={draft.provider} onChange={(event) => {
const provider = event.target.value;
updateDraft(plugin.pluginId, {
provider,
...(provider === 'image_make' ? { llmProviderKeyId: '', llmModel: '' } : {}),
});
}} disabled={!draft.enabled}>
<option value="">选择 Provider</option>
{plugin.providers.map((provider) => <option key={provider} value={provider}>{provider}</option>)}
</select></label>
{plugin.supportsLlm ? <>
{plugin.pluginId === 'asset-generate' && draft.provider === 'image_make' ? (
<div className="asset-image-make-note">
image_make 独立管理本地模型,不读取统一模型中心密钥。
</div>
) : plugin.supportsLlm ? <>
<label>专属 LLM<select value={draft.llmProviderKeyId} onChange={(event) => updateDraft(plugin.pluginId, { llmProviderKeyId: event.target.value, llmModel: '' })} disabled={!draft.enabled}>
<option value="">不使用 LLM</option>
{activeKeys.map((key) => <option key={key.id} value={key.id}>{key.name}</option>)}
@@ -140,6 +163,24 @@ export function AssetGatewayPage() {
{selectedKey?.models.map((model) => <option key={model} value={model}>{model}</option>)}
</select></label>
</> : <div className="asset-no-llm">确定性处理 · 不调用 LLM</div>}
{plugin.pluginId === 'asset-generate' && plugin.purposeCatalog?.length ? (
<fieldset className="asset-purpose-fieldset" disabled={!draft.enabled || draft.provider !== 'image_make'}>
<legend>image_make 生效范围</legend>
<div className="asset-purpose-grid">
{plugin.purposeCatalog.map((purpose) => (
<label key={purpose.id}>
<input
type="checkbox"
checked={Boolean(draft.purposes[purpose.id])}
onChange={(event) => updatePurpose(plugin.pluginId, purpose.id, event.target.checked)}
/>
<span>{purpose.label}<small>{purpose.presetId}</small></span>
</label>
))}
</div>
<p>信息流缩略图仍由 MindSpace 从封面源图派生,不会重复调用生图模型。</p>
</fieldset>
) : null}
</div>
<div className="asset-plugin-footer"><span className={`asset-status ${draft.enabled ? 'is-on' : ''}`}>{draft.enabled ? '待保存为启用' : '默认安全关闭'}</span><button type="button" className="send-btn" disabled={busy === plugin.pluginId} onClick={() => void savePlugin(plugin)}>{busy === plugin.pluginId ? '保存中…' : '保存配置'}</button></div>
</section>;
File diff suppressed because it is too large Load Diff
+285
View File
@@ -0,0 +1,285 @@
import { useEffect, useState } from 'react';
import {
fetchImageQuotaConfig,
fetchImageQuotaLedger,
patchImageQuotaPlan,
} from '../../api/client';
import type { ImageQuotaLedgerEntry, PlanDefinition } from '../../types';
import { Pagination } from '../../components/Pagination';
import { formatTime } from '../utils/format';
type Tab = 'plans' | 'ledger';
function fmtQuota(value: number | null | undefined, unlimited = false) {
if (unlimited || value == null) return '无限';
return String(value);
}
const REASON_LABELS: Record<string, string> = {
admin_grant: '管理员充值',
admin_adjust: '管理员调整',
consume: '生图消费',
period_reset: '周期重置',
plan_change: '套餐变更',
};
export function ImageQuotaPage() {
const [tab, setTab] = useState<Tab>('plans');
return (
<div className="admin-page">
<div className="admin-page-head">
<h2>图片生成额度</h2>
<p className="muted">
用户有剩余额度时才能调用 image_make 生图;套餐默认额度中 0 表示无限。用户级充值请在「用户管理 → 用户详情」中操作。
</p>
</div>
<div className="admin-card" style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<button
type="button"
className={tab === 'plans' ? 'send-btn' : 'ghost-btn'}
onClick={() => setTab('plans')}
>
套餐默认额度
</button>
<button
type="button"
className={tab === 'ledger' ? 'send-btn' : 'ghost-btn'}
onClick={() => setTab('ledger')}
>
额度流水
</button>
</div>
{tab === 'plans' ? <PlansTab /> : <LedgerTab />}
</div>
);
}
function PlansTab() {
const [plans, setPlans] = useState<PlanDefinition[]>([]);
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [loading, setLoading] = useState(false);
const [busyPlan, setBusyPlan] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
const load = async () => {
setLoading(true);
setError(null);
try {
const result = await fetchImageQuotaConfig();
setPlans(result.plans);
setDrafts(Object.fromEntries(result.plans.map((plan) => [plan.planType, String(plan.periodImages)])));
} catch (err) {
setError(err instanceof Error ? err.message : '加载失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
void load();
}, []);
const savePlan = async (planType: string) => {
const raw = drafts[planType];
const periodImages = Math.floor(Number(raw));
if (!Number.isFinite(periodImages) || periodImages < 0) {
setError('额度必须是非负整数');
return;
}
setBusyPlan(planType);
setError(null);
setMessage(null);
try {
await patchImageQuotaPlan(planType, periodImages);
setMessage(`已更新 ${planType} 默认图片额度`);
await load();
} catch (err) {
setError(err instanceof Error ? err.message : '保存失败');
} finally {
setBusyPlan(null);
}
};
return (
<>
{error && <p className="banner banner-error">{error}</p>}
{message && <p className="banner banner-info">{message}</p>}
<section className="admin-card">
{loading && plans.length === 0 ? (
<p className="muted">加载中…</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>套餐</th>
<th>标识</th>
<th>月图片额度</th>
<th>月 Token</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{plans.map((plan) => (
<tr key={plan.planType}>
<td>{plan.name}</td>
<td>
<code className="mono">{plan.planType}</code>
</td>
<td>
<input
type="number"
min="0"
step="1"
value={drafts[plan.planType] ?? String(plan.periodImages)}
onChange={(e) => setDrafts((prev) => ({ ...prev, [plan.planType]: e.target.value }))}
style={{ width: 120 }}
/>
</td>
<td className="muted">
{plan.periodTokens === 0 ? '无限' : plan.periodTokens.toLocaleString('zh-CN')}
</td>
<td>
<button
type="button"
className="ghost-btn"
disabled={loading || busyPlan === plan.planType}
onClick={() => void savePlan(plan.planType)}
>
{busyPlan === plan.planType ? '保存中…' : '保存'}
</button>
</td>
</tr>
))}
{plans.length === 0 && !loading ? (
<tr>
<td colSpan={5} className="muted" style={{ textAlign: 'center', padding: 24 }}>
暂无套餐配置
</td>
</tr>
) : null}
</tbody>
</table>
</div>
)}
</section>
</>
);
}
function LedgerTab() {
const [entries, setEntries] = useState<ImageQuotaLedgerEntry[]>([]);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [total, setTotal] = useState(0);
const [userId, setUserId] = useState('');
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const load = async (p = 1) => {
setLoading(true);
setError(null);
try {
const result = await fetchImageQuotaLedger({
page: p,
pageSize: 30,
userId: userId.trim() || undefined,
});
setEntries(result.entries);
setTotal(result.total);
setTotalPages(result.totalPages);
setPage(p);
} catch (err) {
setError(err instanceof Error ? err.message : '加载失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
void load(1);
}, []);
return (
<>
<section className="admin-card">
<form
className="admin-form"
onSubmit={(e) => {
e.preventDefault();
void load(1);
}}
>
<input
type="search"
placeholder="按 userId 过滤"
value={userId}
onChange={(e) => setUserId(e.target.value)}
/>
<button type="submit" className="send-btn" disabled={loading}>
搜索
</button>
</form>
</section>
{error && <p className="banner banner-error">{error}</p>}
<section className="admin-card">
{loading && entries.length === 0 ? (
<p className="muted">加载中…</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>时间</th>
<th>用户</th>
<th>变动</th>
<th>剩余</th>
<th>原因</th>
<th>备注</th>
</tr>
</thead>
<tbody>
{entries.map((entry) => (
<tr key={entry.id}>
<td className="muted">{formatTime(entry.createdAt)}</td>
<td>
<div>{entry.displayName || entry.username || '—'}</div>
<code className="mono muted">{entry.userId}</code>
</td>
<td style={{ color: entry.delta >= 0 ? 'var(--ok)' : 'var(--danger)' }}>
{entry.delta >= 0 ? `+${entry.delta}` : entry.delta}
</td>
<td>{fmtQuota(entry.balanceAfter)}</td>
<td>{REASON_LABELS[entry.reason] ?? entry.reason}</td>
<td className="muted">{entry.note || entry.refId || '—'}</td>
</tr>
))}
{entries.length === 0 && !loading ? (
<tr>
<td colSpan={6} className="muted" style={{ textAlign: 'center', padding: 24 }}>
暂无流水
</td>
</tr>
) : null}
</tbody>
</table>
</div>
)}
<Pagination
page={page}
totalPages={totalPages}
total={total}
pageSize={30}
onChange={(p) => void load(p)}
/>
</section>
</>
);
}
+5 -3
View File
@@ -16,6 +16,7 @@ import type {
MemoryV2RuntimeStatusResponse,
PersonalMemoryCandidateListResponse,
} from '../../types';
import { isMemoryV2SectionEnabled } from './memory-v2-config';
type BackendKey =
| 'pgvector'
@@ -923,7 +924,8 @@ export function MemoryV2Page() {
{CAPABILITIES.map((capability, index) => {
const section = draft[capability.key];
const currentSection = current[capability.key];
const enabled = Boolean(section.enabled);
const enabled = isMemoryV2SectionEnabled(capability.key, section);
const savedEnabled = isMemoryV2SectionEnabled(capability.key, currentSection);
const accent = BACKEND_ACCENTS[index % BACKEND_ACCENTS.length];
return (
<section
@@ -1015,8 +1017,8 @@ export function MemoryV2Page() {
)}
</div>
)}
<span className={`asset-status ${Boolean(currentSection.enabled) ? 'is-on' : ''}`}>
当前保存:{Boolean(currentSection.enabled) ? '启用' : '关闭'}
<span className={`asset-status ${savedEnabled ? 'is-on' : ''}`}>
当前保存:{savedEnabled ? '启用' : '关闭'}
</span>
<button
type="button"
+251 -22
View File
@@ -1,23 +1,75 @@
import { useEffect, useState } from 'react';
import { getMindSearchConfig, updateMindSearchConfig } from '../../api/client';
import type { MindSearchConfig } from '../../types';
import {
getMindSearchConfig,
listLlmProviderKeys,
testLlmProviderKey,
testMindSearchService,
updateMindSearchConfig,
} from '../../api/client';
import type {
LlmProviderKeyRow,
MindSearchConfig,
MindSearchRoutes,
MindSearchService,
} from '../../types';
const builtInServices: MindSearchService[] = [
{ id: 'searxng', name: 'SearXNG', kind: 'provider', adapter: 'searxng', capabilities: ['search.web', 'search.news'], endpoint: '', healthPath: '/config', enabled: false, timeoutMs: 8000, priority: 100 },
{ id: 'github', name: 'GitHub Code', kind: 'provider', adapter: 'github', capabilities: ['search.code'], endpoint: 'https://api.github.com/search/code', healthPath: '', enabled: false, timeoutMs: 8000, priority: 90 },
{ id: 'reader', name: 'Safe Reader', kind: 'reader', adapter: 'reader', capabilities: ['search.read'], endpoint: '', healthPath: '', enabled: false, timeoutMs: 8000, priority: 80 },
{ id: 'deep-search', name: 'TKMind Deep Search', kind: 'orchestrator', adapter: 'research-http', capabilities: ['search.web', 'research.plan', 'research.execute'], endpoint: 'http://127.0.0.1:20100', healthPath: '/health', enabled: false, timeoutMs: 120000, priority: 100, llmProviderKeyId: '', llmModel: '' },
];
const initial: MindSearchConfig = {
enabled: false,
mode: 'off',
providers: { searxng: false, github: false, reader: false },
settings: { searxngEndpoint: '', maxResults: 10, timeoutMs: 8000, readerMaxChars: 12000 },
services: builtInServices,
routes: { web: 'searxng', news: 'searxng', code: 'github', read: 'reader', research: 'deep-search' },
};
const routeLabels: Record<keyof MindSearchRoutes, string> = {
web: '普通网页搜索',
news: '新闻搜索',
code: '代码搜索',
read: '网页读取',
research: '深度研究',
};
function mergeConfig(config: MindSearchConfig): MindSearchConfig {
const configuredServices = config.services ?? [];
const configuredServiceIds = new Set(configuredServices.map((service) => service.id));
const services = configuredServices.length
? [
...configuredServices,
...builtInServices.filter((service) => !configuredServiceIds.has(service.id)),
]
: builtInServices;
return {
...initial,
...config,
settings: { ...initial.settings, ...config.settings },
services,
routes: { ...initial.routes, ...config.routes },
};
}
export function MindSearchPage() {
const [config, setConfig] = useState(initial);
const [llmKeys, setLlmKeys] = useState<LlmProviderKeyRow[]>([]);
const [meta, setMeta] = useState<{ source?: string; updatedAt?: number | null; updatedBy?: string | null }>({});
const [message, setMessage] = useState('加载配置中…');
useEffect(() => {
getMindSearchConfig()
.then((result) => {
setConfig({ ...initial, ...result.config, settings: { ...initial.settings, ...result.config.settings } });
Promise.all([
getMindSearchConfig(),
listLlmProviderKeys().catch(() => [] as LlmProviderKeyRow[]),
])
.then(([result, keys]) => {
setConfig(mergeConfig(result.config));
setLlmKeys(keys.filter((key) => key.status === 'active'));
setMeta(result);
setMessage('');
})
@@ -28,7 +80,7 @@ export function MindSearchPage() {
setMessage('保存中…');
try {
const result = await updateMindSearchConfig(config);
setConfig({ ...initial, ...result.config, settings: { ...initial.settings, ...result.config.settings } });
setConfig(mergeConfig(result.config));
setMeta(result);
setMessage('已保存到数据库;新会话生效,旧会话不受影响');
} catch (error) {
@@ -36,30 +88,207 @@ export function MindSearchPage() {
}
};
const toggleProvider = (key: keyof MindSearchConfig['providers']) =>
setConfig((current) => ({ ...current, providers: { ...current.providers, [key]: !current.providers[key] } }));
const updateSetting = (key: keyof MindSearchConfig['settings'], value: string | number) =>
setConfig((current) => ({ ...current, settings: { ...current.settings, [key]: value } }));
const updateService = (id: string, patch: Partial<MindSearchService>) =>
setConfig((current) => ({
...current,
services: current.services.map((service) => service.id === id ? { ...service, ...patch } : service),
}));
const addService = () => {
const existingIds = new Set(config.services.map((service) => service.id));
let suffix = config.services.length + 1;
while (existingIds.has(`research-${suffix}`)) suffix += 1;
const id = `research-${suffix}`;
setConfig((current) => ({
...current,
services: [...current.services, {
id,
name: 'Research Engine',
kind: 'orchestrator',
adapter: 'research-http',
capabilities: ['search.web', 'research.plan', 'research.execute'],
endpoint: 'http://127.0.0.1:20100',
healthPath: '/health',
enabled: false,
timeoutMs: 30000,
priority: 100,
llmProviderKeyId: '',
llmModel: '',
}],
}));
};
const removeService = (id: string) =>
setConfig((current) => ({
...current,
services: current.services.filter((service) => service.id !== id),
routes: Object.fromEntries(
Object.entries(current.routes).map(([key, value]) => [key, value === id ? '' : value]),
) as unknown as MindSearchRoutes,
}));
const runServiceTest = async (id: string) => {
setMessage(`测试 ${id} 中…`);
try {
const result = await testMindSearchService(id);
setMessage(`${result.ok ? '通过' : '失败'}:${id};${result.message};${result.latencyMs}ms${result.resultCount == null ? '' : `;${result.resultCount} 条结果`}`);
} catch (error) {
setMessage(error instanceof Error ? error.message : '服务测试失败');
}
};
const runLlmTest = async (service: MindSearchService) => {
if (!service.llmProviderKeyId || !service.llmModel) {
setMessage('请先选择 Deep Search 的 LLM 配置和模型');
return;
}
setMessage(`测试 ${service.llmModel} 中…`);
try {
const result = await testLlmProviderKey(service.llmProviderKeyId, service.llmModel);
setMessage(result.ok
? `LLM 通过:${result.model ?? service.llmModel}${result.latencyMs == null ? '' : `;${result.latencyMs}ms`}`
: `LLM 失败:${result.message ?? '模型连接失败'}`);
} catch (error) {
setMessage(error instanceof Error ? error.message : 'LLM 测试失败');
}
};
return (
<section className="admin-page">
<div className="admin-page-header"><div><h1>MindSearch</h1><p>可插拔外部搜索增强。关闭时完全保持原有搜索、记忆和上下文链路。</p></div></div>
<div className="admin-page-header">
<div>
<h1>MindSearch</h1>
<p>可插拔搜索与研究服务。关闭时保持原有搜索、记忆和上下文链路。</p>
</div>
</div>
<div className="admin-card">
<h2>总开关与模式</h2>
<label><input type="checkbox" checked={config.enabled} onChange={(event) => setConfig({ ...config, enabled: event.target.checked, mode: event.target.checked ? (config.mode === 'off' ? 'shadow' : config.mode) : 'off' })} /> 启用 MindSearch</label>
<label>运行模式 <select value={config.mode} onChange={(event) => setConfig({ ...config, mode: event.target.value as MindSearchConfig['mode'] })}><option value="off">关闭</option><option value="shadow">Shadow(只记录,不注入)</option><option value="assist">Assist(补充工具)</option></select></label>
<h2>Provider</h2>
<fieldset><legend>可用 Provider</legend>
<label><input type="checkbox" checked={config.providers.searxng} onChange={() => toggleProvider('searxng')} /> SearXNG Web/News</label>
<label><input type="checkbox" checked={config.providers.github} onChange={() => toggleProvider('github')} /> GitHub Code(Token 通过环境变量配置,不在页面回显)</label>
<label><input type="checkbox" checked={config.providers.reader} onChange={() => toggleProvider('reader')} /> Reader(阻止 localhost/内网地址)</label>
</fieldset>
<div className="admin-form">
<label className="search-service-toggle">
<input
type="checkbox"
checked={config.enabled}
onChange={(event) => setConfig({
...config,
enabled: event.target.checked,
mode: event.target.checked ? (config.mode === 'off' ? 'shadow' : config.mode) : 'off',
})}
/>
<span>启用 MindSearch</span>
</label>
<label>
<span>运行模式</span>
<select value={config.mode} onChange={(event) => setConfig({ ...config, mode: event.target.value as MindSearchConfig['mode'] })}>
<option value="off">关闭</option>
<option value="shadow">Shadow(只记录,不注入)</option>
<option value="assist">Assist(补充工具)</option>
</select>
</label>
</div>
<h2>服务注册表</h2>
<p>服务独立部署;后台只管理连接、路由和健康检查,不直接操作 Docker 或生产进程。测试使用已保存配置。</p>
<div className="search-service-grid">
{config.services.map((service) => {
const selectedLlmKey = llmKeys.find((key) => key.id === service.llmProviderKeyId);
return (
<fieldset key={service.id} className="search-service-card">
<legend>{service.name}({service.id})</legend>
<label className="search-service-toggle"><input type="checkbox" checked={service.enabled} onChange={(event) => updateService(service.id, { enabled: event.target.checked })} /><span>启用服务</span></label>
<div className="admin-form">
<label><span>名称</span><input value={service.name} onChange={(event) => updateService(service.id, { name: event.target.value })} /></label>
<label>
<span>类型</span>
<select value={service.kind} onChange={(event) => updateService(service.id, { kind: event.target.value as MindSearchService['kind'] })}>
<option value="provider">Provider</option>
<option value="reader">Reader</option>
<option value="orchestrator">Orchestrator</option>
</select>
</label>
<label>
<span>适配器</span>
<select value={service.adapter} onChange={(event) => updateService(service.id, { adapter: event.target.value as MindSearchService['adapter'] })}>
<option value="searxng">SearXNG</option>
<option value="github">GitHub</option>
<option value="reader">Reader</option>
<option value="research-http">Research HTTP</option>
</select>
</label>
<label><span>健康检查路径</span><input value={service.healthPath} placeholder="/health" onChange={(event) => updateService(service.id, { healthPath: event.target.value })} /></label>
<label className="form-span-all"><span>Endpoint</span><input value={service.endpoint} placeholder="http://127.0.0.1:20100" onChange={(event) => updateService(service.id, { endpoint: event.target.value })} /></label>
<label className="form-span-all"><span>Capabilities</span><input value={service.capabilities.join(', ')} onChange={(event) => updateService(service.id, { capabilities: event.target.value.split(',').map((item) => item.trim()).filter(Boolean) })} /></label>
<label><span>超时(毫秒)</span><input type="number" min={1000} max={120000} value={service.timeoutMs} onChange={(event) => updateService(service.id, { timeoutMs: Number(event.target.value) })} /></label>
<label><span>优先级</span><input type="number" min={1} max={1000} value={service.priority} onChange={(event) => updateService(service.id, { priority: Number(event.target.value) })} /></label>
{service.adapter === 'research-http' && <>
<label className="form-span-all">
<span>规划与报告 LLM(可选)</span>
<select
value={service.llmProviderKeyId ?? ''}
onChange={(event) => {
const key = llmKeys.find((item) => item.id === event.target.value);
updateService(service.id, {
llmProviderKeyId: event.target.value,
llmModel: key?.defaultModel ?? '',
});
}}
>
<option value="">不使用 LLM(确定性降级)</option>
{service.llmProviderKeyId && !selectedLlmKey
&& <option value={service.llmProviderKeyId}>原 LLM 配置已停用或删除</option>}
{llmKeys.map((key) => (
<option key={key.id} value={key.id}>{key.name} · {key.providerLabel}</option>
))}
</select>
</label>
<label className="form-span-all">
<span>模型</span>
<select
value={service.llmModel ?? ''}
disabled={!selectedLlmKey}
onChange={(event) => updateService(service.id, { llmModel: event.target.value })}
>
{!selectedLlmKey && <option value="">请先选择 LLM 配置</option>}
{selectedLlmKey && service.llmModel && !selectedLlmKey.models.includes(service.llmModel)
&& <option value={service.llmModel}>原模型已不可用:{service.llmModel}</option>}
{selectedLlmKey?.models.map((model) => <option key={model} value={model}>{model}</option>)}
</select>
</label>
<p className="search-llm-hint form-span-all">密钥复用“统一模型中心”,不会保存到 MindSearch 配置或下发给 Deep Search 服务。</p>
</>}
</div>
<div className="search-service-actions">
<button className="send-btn" type="button" onClick={() => runServiceTest(service.id)}>测试已保存配置</button>
{service.adapter === 'research-http' && service.llmProviderKeyId && service.llmModel
&& <button type="button" onClick={() => runLlmTest(service)}>测试 LLM</button>}
{!['searxng', 'github', 'reader', 'deep-search'].includes(service.id) && <button type="button" onClick={() => removeService(service.id)}>移除</button>}
</div>
</fieldset>
);
})}
</div>
<button className="send-btn" type="button" onClick={addService}>添加 Research Service</button>
<h2>能力路由</h2>
<div className="admin-form">
{(Object.keys(routeLabels) as Array<keyof MindSearchRoutes>).map((route) => (
<label key={route}>
<span>{routeLabels[route]}</span>
<select
value={config.routes[route]}
onChange={(event) => setConfig((current) => ({ ...current, routes: { ...current.routes, [route]: event.target.value } }))}
>
<option value="">未配置</option>
{config.services.map((service) => <option key={service.id} value={service.id}>{service.name}({service.id})</option>)}
</select>
</label>
))}
</div>
<h2>运行参数</h2>
<label>SearXNG 地址 <input value={config.settings.searxngEndpoint} placeholder="http://127.0.0.1:8080/search" onChange={(event) => updateSetting('searxngEndpoint', event.target.value)} /></label>
<label>最大结果数 <input type="number" min={1} max={20} value={config.settings.maxResults} onChange={(event) => updateSetting('maxResults', Number(event.target.value))} /></label>
<label>Provider 超时(毫秒) <input type="number" min={1000} max={30000} value={config.settings.timeoutMs} onChange={(event) => updateSetting('timeoutMs', Number(event.target.value))} /></label>
<label>Reader 最大字符数 <input type="number" min={1000} max={50000} value={config.settings.readerMaxChars} onChange={(event) => updateSetting('readerMaxChars', Number(event.target.value))} /></label>
<button type="button" onClick={save}>保存配置</button>
<div className="admin-form">
<label><span>最大结果数</span><input type="number" min={1} max={20} value={config.settings.maxResults} onChange={(event) => updateSetting('maxResults', Number(event.target.value))} /></label>
<label><span>默认 Provider 超时(毫秒)</span><input type="number" min={1000} max={30000} value={config.settings.timeoutMs} onChange={(event) => updateSetting('timeoutMs', Number(event.target.value))} /></label>
<label><span>Reader 最大字符数</span><input type="number" min={1000} max={50000} value={config.settings.readerMaxChars} onChange={(event) => updateSetting('readerMaxChars', Number(event.target.value))} /></label>
</div>
<button className="send-btn" type="button" onClick={save}>保存配置</button>
{message && <p role="status">{message}</p>}
<p>配置来源:{meta.source === 'admin' ? '数据库' : '环境变量默认值'};最后更新:{meta.updatedAt ? new Date(meta.updatedAt).toLocaleString() : '尚未保存'}{meta.updatedBy ? `;操作人:${meta.updatedBy}` : ''}</p>
</div>
+383
View File
@@ -0,0 +1,383 @@
import { useEffect, useMemo, useState } from 'react';
import {
getOrchestratorCanaryReadiness,
getOrchestratorConfig,
getOrchestratorExecutionPlans,
getOrchestratorRuntime,
getOrchestratorShadowRun,
getOrchestratorShadowRuns,
updateOrchestratorConfig,
} from '../../api/client';
import type {
OrchestratorCanaryReadiness,
OrchestratorConfig,
OrchestratorConfigState,
OrchestratorExecutionPlanList,
OrchestratorServiceHealth,
OrchestratorShadowRunDetail,
OrchestratorShadowRunList,
} from '../../types/orchestrator';
const runtimeReasons: Record<string, string> = {
mode_off: '当前为关闭模式,所有任务继续由 Native Agent Run 执行。',
service_url_missing: '尚未配置 Orchestrator 服务地址,LangGraph 不会接管任务。',
kill_switch: '环境级紧急熔断已开启,强制回退 Native。',
execution_gate_disabled: '执行交接闸门被硬锁定,当前仅生成 Dry-run 决策。',
environment_execution_gate_disabled: 'memindadm 已请求交接,但环境闸门仍关闭。',
};
const readinessLabels: Record<string, string> = {
shadow_mode: '保持 Shadow',
service_healthy: '服务健康',
durable_checkpoint: '持久化 checkpoint',
durable_executor_job_store: '持久化 Executor Job Store',
observe_only: '仅观察不执行',
sample_volume: '有效样本量',
shadow_success_rate: 'Shadow 成功率',
shadow_skip_rate: 'Shadow 跳过率',
latency_coverage: '延迟数据覆盖率',
latency_p95: '延迟 P95',
native_settled_rate: 'Native 终态覆盖率',
session_coverage: '真实会话覆盖',
sample_freshness: '最近样本新鲜度',
complete_window: '统计窗口完整',
};
function listToText(values: string[]) {
return values.join('\n');
}
function textToList(value: string) {
return [...new Set(value.split(/\r?\n|,/).map((item) => item.trim()).filter(Boolean))];
}
function formatTime(value?: number | null) {
return value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—';
}
function formatPercent(value?: number | null) {
return value == null ? '—' : `${(value * 100).toFixed(1)}%`;
}
function formatLatency(value?: number | null) {
return value == null ? '—' : `${value} ms`;
}
function shortId(value: string) {
return value.length > 16 ? `${value.slice(0, 8)}…${value.slice(-6)}` : value;
}
function readinessValue(check: OrchestratorCanaryReadiness['checks'][number]) {
if (check.actual == null) return '无数据';
if (['shadow_success_rate', 'latency_coverage', 'native_settled_rate'].includes(check.id)) {
return formatPercent(Number(check.actual));
}
if (check.id === 'latency_p95') return formatLatency(Number(check.actual));
if (check.id === 'sample_freshness') return `${Number(check.actual).toFixed(1)} 小时`;
if (typeof check.actual === 'boolean') return check.actual ? '是' : '否';
return String(check.actual);
}
export function OrchestratorPage() {
const [state, setState] = useState<OrchestratorConfigState | null>(null);
const [draft, setDraft] = useState<OrchestratorConfig | null>(null);
const [workflowAllowlist, setWorkflowAllowlist] = useState('');
const [userAllowlist, setUserAllowlist] = useState('');
const [shadow, setShadow] = useState<OrchestratorShadowRunList | null>(null);
const [plans, setPlans] = useState<OrchestratorExecutionPlanList | null>(null);
const [readiness, setReadiness] = useState<OrchestratorCanaryReadiness | null>(null);
const [health, setHealth] = useState<OrchestratorServiceHealth | null>(null);
const [detail, setDetail] = useState<OrchestratorShadowRunDetail | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [checking, setChecking] = useState(false);
const [error, setError] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
const load = async () => {
setLoading(true);
setError(null);
try {
const [configState, shadowState, planState, readinessState] = await Promise.all([
getOrchestratorConfig(),
getOrchestratorShadowRuns({ hours: 24, limit: 100 }),
getOrchestratorExecutionPlans({ hours: 24, limit: 100 }),
getOrchestratorCanaryReadiness(),
]);
setState(configState);
setDraft(configState.config);
setWorkflowAllowlist(listToText(configState.config.workflowAllowlist));
setUserAllowlist(listToText(configState.config.userAllowlist));
setShadow(shadowState);
setPlans(planState);
setReadiness(readinessState);
} catch (err) {
setError(err instanceof Error ? err.message : 'Orchestrator 数据加载失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
void load();
}, []);
const normalizedDraft = useMemo(() => draft ? {
...draft,
workflowAllowlist: textToList(workflowAllowlist),
userAllowlist: textToList(userAllowlist),
} : null, [draft, workflowAllowlist, userAllowlist]);
const dirty = Boolean(
state && normalizedDraft && JSON.stringify(state.config) !== JSON.stringify(normalizedDraft),
);
const save = async () => {
if (!normalizedDraft) return;
if (['canary', 'active'].includes(normalizedDraft.mode) && !normalizedDraft.serviceUrl) {
setError('Canary / Active 模式必须先配置 Orchestrator URL。');
return;
}
if (
normalizedDraft.executionEnabled
&& !window.confirm('确认请求执行交接?环境闸门关闭时仍只会 Dry-run。')
) {
return;
}
setSaving(true);
setError(null);
setMessage(null);
try {
const result = await updateOrchestratorConfig(normalizedDraft);
setState(result);
setDraft(result.config);
setWorkflowAllowlist(listToText(result.config.workflowAllowlist));
setUserAllowlist(listToText(result.config.userAllowlist));
setMessage(`Orchestrator 配置 v${result.configVersion} 已保存。`);
} catch (err) {
setError(err instanceof Error ? err.message : '保存失败');
} finally {
setSaving(false);
}
};
const checkHealth = async () => {
setChecking(true);
setError(null);
try {
const result = await getOrchestratorRuntime();
setHealth(result.serviceHealth);
} catch (err) {
setError(err instanceof Error ? err.message : '服务检查失败');
} finally {
setChecking(false);
}
};
const openDetail = async (runId: string) => {
setError(null);
try {
setDetail(await getOrchestratorShadowRun(runId));
} catch (err) {
setError(err instanceof Error ? err.message : 'Run 详情加载失败');
}
};
if (loading) return <div className="admin-page"><p>正在加载 Workflow Orchestrator…</p></div>;
if (!state || !draft) {
return <div className="admin-page"><p className="banner banner-error">{error ?? '配置不可用'}</p></div>;
}
const runtimeMessage = state.runtime.reason
? (runtimeReasons[state.runtime.reason] ?? state.runtime.reason)
: state.runtime.shadowsLangGraph
? 'Shadow 已生效:Native 继续执行,LangGraph 只观察。'
: state.runtime.executesLangGraph
? '执行交接已开启。'
: '配置有效。';
return (
<div className="admin-page orchestrator-page">
<div className="admin-page-head">
<h2>Workflow Orchestrator</h2>
<p className="muted">
LangGraph 以可插拔服务接入;Off 与 Shadow 不改变现有 Native Agent Run 执行路径。
</p>
</div>
{error && <p className="banner banner-error">{error}</p>}
{message && <p className="banner banner-info">{message}</p>}
<section className="admin-card">
<div className="orchestrator-summary">
<div><span>配置版本</span><strong>v{state.configVersion}</strong></div>
<div><span>运行状态</span><strong>{state.runtime.effective ? '有效' : '安全回退'}</strong></div>
<div><span>配置来源</span><strong>{state.source}</strong></div>
<div><span>执行交接</span><strong>{state.runtime.executionHandoff.enabled ? '已开启' : 'Dry-run 锁定'}</strong></div>
<div><span>更新时间</span><strong>{formatTime(state.updatedAt)}</strong></div>
</div>
<p className={`orchestrator-state ${state.runtime.reason === 'kill_switch' ? 'danger' : ''}`}>
{runtimeMessage}
</p>
</section>
<section className="admin-card">
<div className="orchestrator-section-head">
<div>
<h2>Executor Gateway</h2>
<p className="muted">执行器默认关闭,最终状态以 Orchestrator 健康检查为准。</p>
</div>
</div>
<div className="orchestrator-executors">
{state.executors.map((executor) => (
<article key={executor.id}>
<div><strong>{executor.label}</strong><span>{executor.status}</span></div>
<p>{executor.capabilities.join(' · ') || '无能力声明'}</p>
<small>dispatch {executor.dispatchImplemented ? 'implemented' : 'disabled'}</small>
</article>
))}
</div>
</section>
<section className="admin-card">
<div className="orchestrator-section-head">
<div>
<h2>Shadow 运行观测</h2>
<p className="muted">最近 24 小时 Native 与 LangGraph 观察结果,不改变执行权。</p>
</div>
<button type="button" className="ghost-btn" onClick={() => void load()}>刷新</button>
</div>
{readiness && (
<div className={`orchestrator-readiness ${readiness.ready ? 'ready' : ''}`}>
<div>
<strong>Canary 准入评估</strong>
<b>{readiness.ready ? '达到门槛,等待人工审批' : '继续保持 Shadow'}</b>
</div>
<p>
有效样本 {readiness.samples.eligibleObservations} / {readiness.thresholds.minObservations}
{' · '}排除 smoke {readiness.samples.excludedSynthetic}
{' · '}真实会话 {readiness.samples.distinctSessions} / {readiness.thresholds.minDistinctSessions}
</p>
<div className="orchestrator-checks">
{readiness.checks.map((check) => (
<span key={check.id} className={check.passed ? 'passed' : 'blocked'}>
{check.passed ? '通过' : '阻塞'} · {readinessLabels[check.id] ?? check.id}:{readinessValue(check)}
</span>
))}
</div>
</div>
)}
<div className="orchestrator-metrics">
<div><span>观察请求</span><strong>{shadow?.metrics.observations ?? '—'}</strong></div>
<div><span>成功率</span><strong>{formatPercent(shadow?.metrics.successRate)}</strong></div>
<div><span>失败数</span><strong>{shadow?.metrics.failures ?? '—'}</strong></div>
<div><span>延迟 P95</span><strong>{formatLatency(shadow?.metrics.latencyP95Ms)}</strong></div>
<div><span>Native 成功 / 失败</span><strong>{shadow ? `${shadow.metrics.nativeSucceeded} / ${shadow.metrics.nativeFailed}` : '—'}</strong></div>
</div>
<div className="admin-table-wrap">
<table className="admin-table">
<thead><tr><th>时间</th><th>Run</th><th>Shadow</th><th>Native</th><th>延迟</th><th>任务 / Adapter</th></tr></thead>
<tbody>
{(shadow?.runs ?? []).map((run) => (
<tr key={run.eventId}>
<td>{formatTime(run.observedAt)}</td>
<td><button type="button" className="ghost-btn" onClick={() => void openDetail(run.runId)}>{shortId(run.runId)}</button></td>
<td>{run.shadowStatus}</td>
<td>{run.nativeStatus}</td>
<td>{formatLatency(run.latencyMs)}</td>
<td>{run.taskType ?? '—'}{run.synthetic ? '(smoke)' : ''}<small>{run.executorAdapter ?? '—'}</small></td>
</tr>
))}
{!shadow?.runs.length && <tr><td colSpan={6}>当前没有 Shadow 结果。</td></tr>}
</tbody>
</table>
</div>
{detail && (
<div className="orchestrator-detail">
<div className="orchestrator-section-head">
<div><strong>Run 详情:{detail.native.runId}</strong><p className="muted">Native {detail.native.status} · LangGraph {detail.remote.available ? 'available' : 'unavailable'}</p></div>
<button type="button" className="ghost-btn" onClick={() => setDetail(null)}>关闭</button>
</div>
<div>
<pre>{JSON.stringify(detail.remote.state, null, 2)}</pre>
<pre>{JSON.stringify(detail.remote.events, null, 2)}</pre>
</div>
</div>
)}
</section>
<section className="admin-card">
<div className="orchestrator-section-head">
<div><h2>执行路由 Dry-run</h2><p className="muted">候选路由仅观测,实际执行引擎必须保持 Native。</p></div>
</div>
{(plans?.metrics.handoffAllowed ?? 0) > 0 && (
<p className="banner banner-error">检测到 handoffAllowed=true,请立即检查执行闸门。</p>
)}
<div className="orchestrator-metrics">
<div><span>路由决策</span><strong>{plans?.metrics.decisions ?? '—'}</strong></div>
<div><span>候选命中率</span><strong>{formatPercent(plans?.metrics.candidateSelectionRate)}</strong></div>
<div><span>LangGraph / Native</span><strong>{plans ? `${plans.metrics.candidateSelections} / ${plans.metrics.nativeSelections}` : '—'}</strong></div>
<div><span>Native 终态覆盖</span><strong>{formatPercent(plans?.metrics.nativeSettledRate)}</strong></div>
<div><span>真实会话</span><strong>{plans?.metrics.distinctSessions ?? '—'}</strong></div>
</div>
<div className="admin-table-wrap">
<table className="admin-table">
<thead><tr><th>时间</th><th>Run</th><th>模式</th><th>候选 → 实际</th><th>原因</th><th>Native</th></tr></thead>
<tbody>
{(plans?.plans ?? []).map((plan) => (
<tr key={plan.eventId}>
<td>{formatTime(plan.plannedAt)}</td>
<td className="mono">{shortId(plan.runId)}</td>
<td>{plan.mode ?? '—'}</td>
<td>{plan.candidateEngine} → {plan.effectiveEngine}</td>
<td>{plan.candidateReason ?? plan.reason ?? '—'}</td>
<td>{plan.nativeStatus}</td>
</tr>
))}
{!plans?.plans.length && <tr><td colSpan={6}>当前没有 Dry-run 路由决策。</td></tr>}
</tbody>
</table>
</div>
</section>
<section className="admin-card">
<h2>路由与服务配置</h2>
<div className="orchestrator-form-grid">
<label><span>运行模式</span><select value={draft.mode} onChange={(event) => setDraft({ ...draft, mode: event.target.value as OrchestratorConfig['mode'] })}>
<option value="off">Off — Native only</option>
<option value="shadow">Shadow — Native 执行,LangGraph 观察</option>
<option value="canary">Canary — 白名单/百分比灰度</option>
<option value="active">Active — 工作流白名单接管</option>
</select></label>
<label><span>主执行引擎</span><select value={draft.primaryEngine} onChange={(event) => setDraft({ ...draft, primaryEngine: event.target.value })}>
{state.engines.map((engine) => <option key={engine.id} value={engine.id}>{engine.label}{engine.configured ? '' : '(未配置)'}</option>)}
</select></label>
<label><span>灰度百分比</span><input type="number" min={0} max={100} value={draft.rolloutPercent} onChange={(event) => setDraft({ ...draft, rolloutPercent: Number(event.target.value) })} /></label>
<label><span>请求超时(毫秒)</span><input type="number" min={500} max={60000} value={draft.requestTimeoutMs} onChange={(event) => setDraft({ ...draft, requestTimeoutMs: Number(event.target.value) })} /></label>
<label className="wide"><span>Orchestrator URL</span><input value={draft.serviceUrl} onChange={(event) => setDraft({ ...draft, serviceUrl: event.target.value })} placeholder="http://127.0.0.1:8093" /></label>
</div>
<div className="orchestrator-health">
<span>{health ? `${health.ok ? '健康' : '不可用'}(${health.status},${health.latencyMs} ms)` : '尚未检查服务连接'}</span>
<button type="button" className="ghost-btn" onClick={() => void checkHealth()} disabled={checking}>{checking ? '检查中…' : '测试连接'}</button>
</div>
<div className="orchestrator-toggles">
<label><input type="checkbox" checked={draft.requireHealthy} onChange={(event) => setDraft({ ...draft, requireHealthy: event.target.checked })} />接管前要求服务健康</label>
<label><input type="checkbox" checked={draft.fallbackToNative} onChange={(event) => setDraft({ ...draft, fallbackToNative: event.target.checked })} />不可用时回退 Native</label>
<label className="handoff"><input type="checkbox" checked={draft.executionEnabled} onChange={(event) => setDraft({ ...draft, executionEnabled: event.target.checked })} />请求启用执行交接(仍受环境闸门与 Kill Switch 约束)</label>
</div>
<div className="orchestrator-allowlists">
<label><span>工作流白名单</span><textarea rows={6} value={workflowAllowlist} onChange={(event) => setWorkflowAllowlist(event.target.value)} /></label>
<label><span>用户白名单</span><textarea rows={6} value={userAllowlist} onChange={(event) => setUserAllowlist(event.target.value)} /></label>
</div>
<div className="admin-actions orchestrator-actions">
<button type="button" className="ghost-btn" onClick={() => void load()} disabled={saving}>放弃修改</button>
<button type="button" className="send-btn" onClick={() => void save()} disabled={saving || !dirty}>{saving ? '保存中…' : '保存配置'}</button>
</div>
</section>
</div>
);
}
+111 -2
View File
@@ -1,12 +1,12 @@
import { useEffect, useState } from 'react';
import { Link, Navigate, useParams } from 'react-router-dom';
import { getAdminUser, rechargeUser, updateAdminUser } from '../../api/client';
import { getAdminUser, rechargeUser, updateAdminUser, fetchUserImageQuota, setUserImageQuota } from '../../api/client';
import { CapabilitySettings } from '../../components/CapabilitySettings';
import { PolicySettings } from '../../components/PolicySettings';
import { SkillSettings } from '../../components/SkillSettings';
import { useAdminUsers } from '../hooks/useAdminUsers';
import { formatYuan } from '../utils/format';
import type { PortalUser } from '../../types';
import type { ImageQuotaView, PortalUser } from '../../types';
function formatBytes(bytes: number) {
if (bytes < 1024) return `${bytes} B`;
@@ -23,6 +23,10 @@ export function UserDetailPage() {
const [message, setMessage] = useState<string | null>(null);
const [recharge, setRecharge] = useState({ amountYuan: '10', note: '' });
const [spaceQuotaMb, setSpaceQuotaMb] = useState('5');
const [imageQuota, setImageQuota] = useState<ImageQuotaView | null>(null);
const [imageQuotaLoading, setImageQuotaLoading] = useState(false);
const [imageRemaining, setImageRemaining] = useState('');
const [imageGrantNote, setImageGrantNote] = useState('');
useEffect(() => {
if (!user?.spaceQuotaBytes) return;
@@ -57,6 +61,36 @@ export function UserDetailPage() {
};
}, [userId, users]);
useEffect(() => {
if (!user || user.role !== 'user') {
setImageQuota(null);
return;
}
let cancelled = false;
setImageQuotaLoading(true);
void fetchUserImageQuota(user.id)
.then((result) => {
if (!cancelled) setImageQuota(result.quota);
})
.catch(() => {
if (!cancelled) setImageQuota(null);
})
.finally(() => {
if (!cancelled) setImageQuotaLoading(false);
});
return () => {
cancelled = true;
};
}, [user?.id, user?.role]);
useEffect(() => {
if (!imageQuota || imageQuota.unlimited || imageQuota.remaining == null) {
setImageRemaining('');
return;
}
setImageRemaining(String(imageQuota.remaining));
}, [imageQuota?.remaining, imageQuota?.unlimited]);
const handleRecharge = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
@@ -75,6 +109,45 @@ export function UserDetailPage() {
}
};
const handleImageQuotaSave = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
setMessage(null);
setLocalError(null);
setError(null);
if (!imageQuota) {
setLocalError('暂无额度信息,用户可能尚无有效订阅');
return;
}
if (imageQuota.unlimited) {
setLocalError('当前为无限额度套餐,无法在此调整');
return;
}
const targetRemaining = Math.floor(Number(imageRemaining));
if (!Number.isFinite(targetRemaining) || targetRemaining < 0) {
setLocalError('请输入非负整数剩余额度');
return;
}
if (targetRemaining === imageQuota.remaining) {
setMessage('额度未变化');
return;
}
try {
const result = await setUserImageQuota(user.id, { remaining: targetRemaining }, imageGrantNote.trim());
setImageQuota(result.quota);
setMessage(result.unchanged ? '额度未变化' : '图片额度已更新');
setImageGrantNote('');
} catch (err) {
setLocalError(err instanceof Error ? err.message : '图片额度设置失败');
}
};
const imageQuotaSummary = imageQuota
? imageQuota.unlimited
? '无限'
: `剩余 ${imageQuota.remaining ?? 0} / 总计 ${imageQuota.total ?? 0}(套餐 ${imageQuota.limit} + 充值 ${imageQuota.bonus},已用 ${imageQuota.used})`
: '';
if (!loading && !user && !error) {
return <Navigate to="/users" replace />;
}
@@ -186,6 +259,42 @@ export function UserDetailPage() {
</form>
</section>
<section className="admin-card">
<h2>图片生成额度</h2>
{imageQuotaLoading ? (
<p className="muted">加载中…</p>
) : (
<p className="muted">{imageQuotaSummary || '暂无额度信息(用户可能尚无订阅)'}</p>
)}
<p className="muted">
直接设置本周期剩余可用张数。若目标低于当前套餐额度,会自动下调该用户的周期额度上限。
</p>
<form className="admin-form" onSubmit={handleImageQuotaSave}>
<input
placeholder="剩余额度(张)"
type="number"
min="0"
step="1"
value={imageRemaining}
onChange={(e) => setImageRemaining(e.target.value)}
disabled={!imageQuota || imageQuota.unlimited}
/>
<input
placeholder="备注"
value={imageGrantNote}
onChange={(e) => setImageGrantNote(e.target.value)}
disabled={!imageQuota || imageQuota.unlimited}
/>
<button
type="submit"
className="send-btn"
disabled={!imageQuota || imageQuota.unlimited}
>
保存额度
</button>
</form>
</section>
<section className="admin-card">
<h2>调整空间</h2>
<p className="muted">
+244 -1
View File
@@ -1,24 +1,31 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
cancelWechatDigest,
clearWechatRoute,
createWechatWebNotification,
getWechatAdminSummary,
getWechatIntentRouterConfig,
getWechatIntentRouterRuntime,
listAdminUsers,
listLlmProviderKeys,
listWechatBindings,
listWechatDeliveries,
listWechatDigests,
listWechatMessages,
listWechatWebNotifications,
patchWechatIntentRouterConfig,
resumeWechatDigest,
updateWechatScheduleLlmConfig,
} from '../../api/client';
import type {
AdminUserRow,
LlmProviderKeyRow,
WechatAdminSummary,
WechatBinding,
WechatDeliveryLog,
WechatDigestSubscription,
WechatIntentRouterAdminConfig,
WechatIntentRouterRuntimeState,
WechatMessage,
WechatWebNotification,
} from '../../types';
@@ -70,6 +77,49 @@ function dateLabel(value?: number | null) {
return value ? formatTime(value) : '—';
}
type IntentRouterForm = {
enabled: boolean;
shadowMode: boolean;
modelProviderKeyId: string;
model: string;
minConfidence: string;
timeoutMs: string;
canaryOpenids: string;
};
function intentRouterToForm(
config: WechatIntentRouterAdminConfig | undefined,
keys: LlmProviderKeyRow[],
): IntentRouterForm {
const keyId = String(config?.modelProviderKeyId ?? '').trim();
const selectedKey = keys.find((item) => item.id === keyId) ?? null;
const model = String(config?.model ?? '').trim()
|| selectedKey?.defaultModel
|| selectedKey?.models?.[0]
|| '';
return {
enabled: Boolean(config?.enabled),
shadowMode: config?.shadowMode !== false,
modelProviderKeyId: keyId,
model,
minConfidence: String(config?.minConfidence ?? 0.65),
timeoutMs: String(config?.timeoutMs ?? 4000),
canaryOpenids: Array.isArray(config?.canaryOpenids) ? config.canaryOpenids.join('\n') : '',
};
}
function intentRouterRuntimeMode(overrides: Record<string, string>) {
const enabled = ['1', 'true', 'yes', 'on'].includes(
String(overrides.MEMIND_WECHAT_INTENT_LLM_ENABLED ?? '').toLowerCase(),
);
const shadow = ['1', 'true', 'yes', 'on'].includes(
String(overrides.MEMIND_WECHAT_INTENT_LLM_SHADOW ?? '').toLowerCase(),
);
if (!enabled) return '关闭(仅规则意图)';
if (shadow) return 'Shadow 观测(行为不变)';
return '已激活(chat.general 可升级为 page.generate)';
}
export function WechatPage() {
const [summary, setSummary] = useState<WechatAdminSummary | null>(null);
const [bindings, setBindings] = useState<WechatBinding[]>([]);
@@ -91,12 +141,27 @@ export function WechatPage() {
const [notifyType, setNotifyType] = useState('manual');
const [notifyChannels, setNotifyChannels] = useState<Array<'web' | 'wechat'>>(['web']);
const [scheduleLlmEnabled, setScheduleLlmEnabled] = useState(false);
const [llmKeys, setLlmKeys] = useState<LlmProviderKeyRow[]>([]);
const [intentForm, setIntentForm] = useState<IntentRouterForm | null>(null);
const [savedIntentForm, setSavedIntentForm] = useState<IntentRouterForm | null>(null);
const [intentRuntime, setIntentRuntime] = useState<WechatIntentRouterRuntimeState | null>(null);
const [intentSaving, setIntentSaving] = useState(false);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const safe = safeSummary(summary);
const intentDirty = useMemo(() => {
if (!intentForm || !savedIntentForm) return false;
return JSON.stringify(intentForm) !== JSON.stringify(savedIntentForm);
}, [intentForm, savedIntentForm]);
const selectedIntentKey = useMemo(
() => llmKeys.find((item) => item.id === intentForm?.modelProviderKeyId) ?? null,
[llmKeys, intentForm?.modelProviderKeyId],
);
const load = useCallback(async () => {
setLoading(true);
setError(null);
@@ -109,6 +174,9 @@ export function WechatPage() {
nextDeliveries,
nextNotifications,
nextUsers,
nextLlmKeys,
nextIntentConfig,
nextIntentRuntime,
] =
await Promise.all([
getWechatAdminSummary(),
@@ -118,6 +186,9 @@ export function WechatPage() {
listWechatDeliveries({ status: deliveryStatus || undefined, limit: 80 }),
listWechatWebNotifications({ status: notificationStatus || undefined, limit: 80 }),
listAdminUsers({ page: 1, pageSize: 200, status: 'active' }),
listLlmProviderKeys().catch(() => [] as LlmProviderKeyRow[]),
getWechatIntentRouterConfig().catch(() => null),
getWechatIntentRouterRuntime().catch(() => null),
]);
setSummary(nextSummary);
setScheduleLlmEnabled(nextSummary.config.scheduleLlmEnabled ?? false);
@@ -128,6 +199,13 @@ export function WechatPage() {
setWebNotifications(nextNotifications);
setUsers(nextUsers.items);
setNotifyUserId((current) => current || nextUsers.items[0]?.id || '');
setLlmKeys(nextLlmKeys);
if (nextIntentConfig) {
const nextForm = intentRouterToForm(nextIntentConfig, nextLlmKeys);
setIntentForm(nextForm);
setSavedIntentForm(nextForm);
}
setIntentRuntime(nextIntentRuntime);
} catch (err) {
setError(err instanceof Error ? err.message : '加载服务号管理失败');
} finally {
@@ -235,6 +313,36 @@ export function WechatPage() {
});
};
const handleSaveIntentRouter = async () => {
if (!intentForm) return;
setIntentSaving(true);
setError(null);
setNotice(null);
try {
const result = await patchWechatIntentRouterConfig({
enabled: intentForm.enabled,
shadowMode: intentForm.shadowMode,
modelProviderKeyId: intentForm.modelProviderKeyId || null,
model: intentForm.model || null,
minConfidence: Number(intentForm.minConfidence) || 0.65,
timeoutMs: Number(intentForm.timeoutMs) || 4000,
canaryOpenids: intentForm.canaryOpenids
.split(/[\s,]+/u)
.map((item) => item.trim())
.filter(Boolean),
});
const nextForm = intentRouterToForm(result, llmKeys);
setIntentForm(nextForm);
setSavedIntentForm(nextForm);
setIntentRuntime(await getWechatIntentRouterRuntime().catch(() => null));
setNotice('微信 LLM 意图路由配置已保存。Portal 会在下次请求时自动热加载。');
} catch (err) {
setError(err instanceof Error ? err.message : '保存失败');
} finally {
setIntentSaving(false);
}
};
return (
<div className="admin-page">
<div className="admin-page-head">
@@ -316,6 +424,141 @@ export function WechatPage() {
</section>
)}
{intentForm ? (
<section className="admin-card">
<div className="admin-card-head">
<div>
<h2>微信 LLM 意图路由</h2>
<p className="muted" style={{ marginTop: 6 }}>
独立于 H5 Router。仅对规则判为 chat.general 的消息做 LLM 二次判定(page.generate vs chat.general)。
</p>
</div>
<button
type="button"
className="ghost-btn"
onClick={() => void handleSaveIntentRouter()}
disabled={busy || intentSaving || !intentDirty}
>
{intentSaving ? '保存中…' : intentDirty ? '保存配置' : '已保存'}
</button>
</div>
<div className="admin-form" style={{ marginTop: 16 }}>
<label>
<input
type="checkbox"
checked={intentForm.enabled}
disabled={busy || intentSaving}
onChange={(event) =>
setIntentForm((current) => current && { ...current, enabled: event.target.checked })
}
/>{' '}
启用 LLM 意图层
</label>
<label>
<input
type="checkbox"
checked={intentForm.shadowMode}
disabled={busy || intentSaving || !intentForm.enabled}
onChange={(event) =>
setIntentForm((current) => current && { ...current, shadowMode: event.target.checked })
}
/>{' '}
Shadow 模式(只观测不改行为)
</label>
<label>
LLM Provider Key
<select
value={intentForm.modelProviderKeyId}
disabled={busy || intentSaving}
onChange={(event) => {
const keyId = event.target.value;
const key = llmKeys.find((item) => item.id === keyId) ?? null;
setIntentForm((current) =>
current
? {
...current,
modelProviderKeyId: keyId,
model: key?.defaultModel || key?.models?.[0] || current.model,
}
: current,
);
}}
>
<option value="">使用全局选中 Key</option>
{llmKeys.map((key) => (
<option key={key.id} value={key.id}>
{key.name} ({key.providerLabel})
</option>
))}
</select>
</label>
<label>
模型
<input
list="wechat-intent-models"
value={intentForm.model}
disabled={busy || intentSaving}
placeholder={selectedIntentKey?.defaultModel || 'deepseek-v4-pro'}
onChange={(event) =>
setIntentForm((current) => current && { ...current, model: event.target.value })
}
/>
<datalist id="wechat-intent-models">
{(selectedIntentKey?.models ?? []).map((model) => (
<option key={model} value={model} />
))}
</datalist>
</label>
<label>
最低置信度
<input
type="number"
min={0}
max={1}
step={0.05}
value={intentForm.minConfidence}
disabled={busy || intentSaving}
onChange={(event) =>
setIntentForm((current) => current && { ...current, minConfidence: event.target.value })
}
/>
</label>
<label>
超时 (ms)
<input
type="number"
min={500}
max={30000}
step={100}
value={intentForm.timeoutMs}
disabled={busy || intentSaving}
onChange={(event) =>
setIntentForm((current) => current && { ...current, timeoutMs: event.target.value })
}
/>
</label>
<label>
Canary OpenID(每行或逗号分隔,留空=全员)
<textarea
value={intentForm.canaryOpenids}
disabled={busy || intentSaving}
rows={3}
placeholder="oXXXX..."
onChange={(event) =>
setIntentForm((current) => current && { ...current, canaryOpenids: event.target.value })
}
/>
</label>
</div>
{intentRuntime ? (
<p className="muted" style={{ marginTop: 12 }}>
运行时:{intentRouterRuntimeMode(intentRuntime.overrides)} · 来源 {intentRuntime.source}
{intentRuntime.updatedAt ? ` · 更新 ${dateLabel(intentRuntime.updatedAt)}` : ''}
</p>
) : null}
</section>
) : null}
<section className="admin-card">
<div className="admin-card-head">
<h2>通知平台</h2>
+34
View File
@@ -0,0 +1,34 @@
import type { MemoryV2AdminSection } from '../../types';
type CapabilityKey =
| 'candidateMemory'
| 'runtimeControl'
| 'policy'
| 'retriever'
| 'lifecycle'
| 'persona'
| 'graph'
| 'userMemory'
| 'pluginHealth';
function modeEnabled(value: unknown) {
const mode = String(value ?? 'off').trim().toLowerCase();
return mode !== '' && mode !== 'off';
}
export function isMemoryV2SectionEnabled(
sectionKey: CapabilityKey,
section: MemoryV2AdminSection | undefined,
): boolean {
const config = section ?? {};
if (sectionKey === 'runtimeControl') {
return Boolean(config.agentResolveEnabled)
|| modeEnabled(config.agentInjectionMode)
|| Boolean(config.promotionEnabled)
|| Boolean(config.compactionV2Enabled)
|| Boolean(config.reflectionEnabled)
|| Boolean(config.lifecycleWorkerEnabled)
|| modeEnabled(config.lifecycleRolloutMode);
}
return Boolean(config.enabled);
}
+333
View File
@@ -8,10 +8,14 @@ import type {
AdminSubscription,
AdminUserRow,
AuthStatus,
BillingAdminConfig,
BillingAdminConfigResponse,
BlockedWord,
CapabilityDefinition,
CapabilityMap,
InsufficientBalanceDetails,
ImageQuotaLedgerEntry,
ImageQuotaView,
LedgerEntry,
LlmConnectionTestResult,
LlmExecutorBinding,
@@ -35,21 +39,39 @@ import type {
MemoryV2AdminConfigResponse,
MemoryV2ModelApiType,
MemoryV2RuntimeStatusResponse,
MemoryV2ConfigRuntimeState,
SkillRuntimeAdminConfig,
SkillRuntimeAdminConfigResponse,
SkillRuntimeCatalogItem,
SkillDefinition,
SkillMap,
UsageRecord,
UsageStatsBucket,
UsageStatsResult,
UsageSummaryResult,
UsageTotals,
WechatAdminSummary,
WechatBinding,
WechatDeliveryLog,
WechatDigestSubscription,
WechatScheduleLlmConfig,
WechatIntentRouterAdminConfig,
WechatIntentRouterConfigState,
WechatIntentRouterRuntimeState,
WechatMessage,
WechatWebNotification,
MindSearchConfig,
MindSearchServiceTestResult,
} from '../types';
import type {
OrchestratorCanaryReadiness,
OrchestratorConfig,
OrchestratorConfigState,
OrchestratorExecutionPlanList,
OrchestratorRuntimeState,
OrchestratorShadowRunDetail,
OrchestratorShadowRunList,
} from '../types/orchestrator';
export class ApiError extends Error {
readonly status: number;
@@ -219,11 +241,15 @@ export async function listAdminUsage(params?: {
userId?: string;
page?: number;
pageSize?: number;
startAt?: number;
endAt?: number;
}): Promise<PagedResult<UsageRecord>> {
const q = new URLSearchParams();
if (params?.userId) q.set('userId', params.userId);
if (params?.page) q.set('page', String(params.page));
if (params?.pageSize) q.set('pageSize', String(params.pageSize));
if (params?.startAt) q.set('startAt', String(params.startAt));
if (params?.endAt) q.set('endAt', String(params.endAt));
const result = await portalFetch<{ records: UsageRecord[]; total: number; page: number; pageSize: number }>(
`/admin-api/usage${q.toString() ? `?${q}` : ''}`,
);
@@ -232,6 +258,146 @@ export async function listAdminUsage(params?: {
return { items: result.records ?? [], total, page: result.page ?? 1, pageSize, totalPages: Math.ceil(total / pageSize) };
}
function toMillis(ts: number) {
return ts >= 1_000_000_000_000 ? ts : ts * 1000;
}
function usageDayKey(createdAt: number) {
const d = new Date(toMillis(createdAt));
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
async function aggregateUsageStatsFromRecords(params: {
userId?: string;
startAt: number;
endAt: number;
}): Promise<UsageStatsResult> {
const bucketMap = new Map<string, UsageStatsBucket>();
let page = 1;
const pageSize = 200;
const maxPages = 50;
const startMs = params.startAt * 1000;
const endMs = params.endAt * 1000 + 999;
while (page <= maxPages) {
const result = await listAdminUsage({
userId: params.userId,
page,
pageSize,
startAt: params.startAt,
endAt: params.endAt,
});
for (const record of result.items) {
const createdMs = toMillis(record.createdAt);
if (createdMs < startMs || createdMs > endMs) continue;
const day = usageDayKey(record.createdAt);
const bucket = bucketMap.get(day) ?? {
day,
count: 0,
inputTokens: 0,
outputTokens: 0,
costCents: 0,
};
bucket.count += 1;
bucket.inputTokens += record.inputTokens;
bucket.outputTokens += record.outputTokens;
bucket.costCents += record.costCents;
bucketMap.set(day, bucket);
}
if (page >= result.totalPages || result.items.length === 0) break;
page += 1;
}
return {
buckets: [...bucketMap.values()].sort((a, b) => a.day.localeCompare(b.day)),
startAt: params.startAt,
endAt: params.endAt,
};
}
function sumUsageBuckets(buckets: UsageStatsBucket[]): UsageTotals {
return buckets.reduce(
(acc, b) => ({
count: acc.count + b.count,
inputTokens: acc.inputTokens + b.inputTokens,
outputTokens: acc.outputTokens + b.outputTokens,
costCents: acc.costCents + b.costCents,
}),
{ count: 0, inputTokens: 0, outputTokens: 0, costCents: 0 },
);
}
export async function getAdminUsageSummary(params?: {
userId?: string;
startAt?: number;
endAt?: number;
}): Promise<UsageSummaryResult> {
const q = new URLSearchParams();
if (params?.userId) q.set('userId', params.userId);
if (params?.startAt) q.set('startAt', String(params.startAt));
if (params?.endAt) q.set('endAt', String(params.endAt));
const suffix = q.toString() ? `?${q}` : '';
try {
return await portalFetch<UsageSummaryResult>(`/admin-api/usage/summary${suffix}`);
} catch (err) {
if (!(err instanceof ApiError) || err.status !== 404) throw err;
}
const allTime = sumUsageBuckets(
(await aggregateUsageStatsFromRecords({
userId: params?.userId,
startAt: 0,
endAt: Math.floor(Date.now() / 1000),
})).buckets,
);
if (!params?.startAt || !params?.endAt) {
return { range: null, allTime };
}
const rangeRows = await getAdminUsageStats({
userId: params.userId,
startAt: params.startAt,
endAt: params.endAt,
});
return {
range: {
...sumUsageBuckets(rangeRows.buckets),
startAt: params.startAt,
endAt: params.endAt,
},
allTime,
};
}
export async function getAdminUsageStats(params: {
userId?: string;
startAt: number;
endAt: number;
}): Promise<UsageStatsResult> {
const q = new URLSearchParams();
if (params.userId) q.set('userId', params.userId);
q.set('startAt', String(params.startAt));
q.set('endAt', String(params.endAt));
const attempts = [
`/admin-api/usage/stats?${q}`,
`/admin-api/usage?${q}&stats=1`,
];
for (const path of attempts) {
try {
return await portalFetch<UsageStatsResult>(path);
} catch (err) {
if (err instanceof ApiError && err.status === 404) continue;
throw err;
}
}
return aggregateUsageStatsFromRecords(params);
}
export async function listAdminLedger(params?: {
userId?: string;
page?: number;
@@ -287,6 +453,25 @@ export async function updateWechatScheduleLlmConfig(
});
}
export async function getWechatIntentRouterConfig(): Promise<WechatIntentRouterAdminConfig> {
const result = await portalFetch<WechatIntentRouterConfigState>('/admin-api/wechat/intent-router/config');
return result.config;
}
export async function patchWechatIntentRouterConfig(
patch: Partial<Omit<WechatIntentRouterAdminConfig, 'updatedAt' | 'updatedBy'>>,
): Promise<WechatIntentRouterAdminConfig> {
const result = await portalFetch<WechatIntentRouterConfigState>('/admin-api/wechat/intent-router/config', {
method: 'PATCH',
body: JSON.stringify(patch),
});
return result.config;
}
export async function getWechatIntentRouterRuntime(): Promise<WechatIntentRouterRuntimeState> {
return portalFetch<WechatIntentRouterRuntimeState>('/admin-api/wechat/intent-router/runtime');
}
export async function getAssetGatewayConfig(): Promise<AssetGatewayConfig> {
return portalFetch('/admin-api/asset-gateway/config');
}
@@ -307,6 +492,7 @@ export async function updateAssetPluginConfig(
provider?: string | null;
llmProviderKeyId?: string | null;
llmModel?: string | null;
purposes?: Record<string, boolean>;
},
): Promise<{ ok: boolean; config: AssetGatewayConfig }> {
return portalFetch(`/admin-api/asset-gateway/plugins/${encodeURIComponent(pluginId)}`, {
@@ -325,6 +511,11 @@ export async function getUmamiSsoUrl(): Promise<string> {
return result.url;
}
export async function getRybbitSsoUrl(): Promise<string> {
const result = await portalFetch<{ url: string }>('/admin-api/analytics/rybbit-sso');
return result.url;
}
export async function updateMindSpaceAdminConfig(
payload: Partial<MindSpaceAdminConfig> & { analytics?: MindSpaceAnalyticsUpdate },
): Promise<MindSpaceAdminConfig> {
@@ -343,6 +534,10 @@ export async function getMemoryV2RuntimeStatus(): Promise<MemoryV2RuntimeStatusR
return portalFetch('/admin-api/memory-v2/status');
}
export async function getMemoryV2ConfigRuntime(): Promise<MemoryV2ConfigRuntimeState> {
return portalFetch('/admin-api/memory-v2/runtime');
}
export async function listPersonalMemoryCandidates(
status = 'candidate',
): Promise<PersonalMemoryCandidateListResponse> {
@@ -668,6 +863,67 @@ export async function updateMindSearchConfig(config: Partial<MindSearchConfig>):
return portalFetch('/admin-api/mindsearch/config', { method: 'PATCH', body: JSON.stringify(config) });
}
export async function testMindSearchService(serviceId: string): Promise<MindSearchServiceTestResult> {
return portalFetch(`/admin-api/mindsearch/services/${encodeURIComponent(serviceId)}/test`, { method: 'POST' });
}
// ── Workflow Orchestrator ─────────────────────────────
export async function getOrchestratorConfig() {
return portalFetch<OrchestratorConfigState>('/admin-api/orchestrator/config');
}
export async function updateOrchestratorConfig(config: OrchestratorConfig) {
return portalFetch<OrchestratorConfigState>('/admin-api/orchestrator/config', {
method: 'PUT',
body: JSON.stringify({ config }),
});
}
export async function getOrchestratorRuntime() {
return portalFetch<OrchestratorRuntimeState>('/admin-api/orchestrator/runtime');
}
export async function getOrchestratorShadowRuns(params: {
hours?: number;
limit?: number;
status?: 'all' | 'succeeded' | 'failed';
} = {}) {
const query = new URLSearchParams();
if (params.hours) query.set('hours', String(params.hours));
if (params.limit) query.set('limit', String(params.limit));
if (params.status) query.set('status', params.status);
return portalFetch<OrchestratorShadowRunList>(
`/admin-api/orchestrator/shadow-runs?${query}`,
);
}
export async function getOrchestratorExecutionPlans(params: {
hours?: number;
limit?: number;
selection?: 'all' | 'candidate' | 'native';
} = {}) {
const query = new URLSearchParams();
if (params.hours) query.set('hours', String(params.hours));
if (params.limit) query.set('limit', String(params.limit));
if (params.selection) query.set('selection', params.selection);
return portalFetch<OrchestratorExecutionPlanList>(
`/admin-api/orchestrator/execution-plans?${query}`,
);
}
export async function getOrchestratorCanaryReadiness() {
return portalFetch<OrchestratorCanaryReadiness>(
'/admin-api/orchestrator/canary-readiness',
);
}
export async function getOrchestratorShadowRun(runId: string) {
return portalFetch<OrchestratorShadowRunDetail>(
`/admin-api/orchestrator/shadow-runs/${encodeURIComponent(runId)}`,
);
}
// ── Policies ──────────────────────────────────────────
export async function listPolicyCatalog(): Promise<PolicyDefinition[]> {
@@ -1050,6 +1306,19 @@ export async function syncSubscriptionPlansToProduction(): Promise<PlanSyncResul
return result.sync;
}
export async function getBillingConfig(): Promise<BillingAdminConfigResponse> {
return portalFetch('/admin-api/billing/config');
}
export async function updateBillingConfig(
config: BillingAdminConfig,
): Promise<BillingAdminConfigResponse> {
return portalFetch('/admin-api/billing/config', {
method: 'PUT',
body: JSON.stringify({ config }),
});
}
export async function listAdminSubscriptions(opts?: {
userId?: string;
status?: string;
@@ -1099,3 +1368,67 @@ export async function getUserSubscription(userId: string): Promise<AdminSubscrip
);
return result.subscription;
}
export async function fetchImageQuotaConfig() {
return portalFetch<{ plans: PlanDefinition[] }>('/admin-api/image-quota/config');
}
export async function patchImageQuotaPlan(planType: string, periodImages: number) {
return portalFetch<{ ok: boolean; plan: PlanDefinition }>(`/admin-api/image-quota/config/${planType}`, {
method: 'PATCH',
body: JSON.stringify({ periodImages }),
});
}
export async function fetchUserImageQuota(userId: string) {
return portalFetch<{
subscription: AdminSubscription;
quota: ImageQuotaView;
ledger: ImageQuotaLedgerEntry[];
}>(`/admin-api/users/${userId}/image-quota`);
}
export async function setUserImageQuota(
userId: string,
payload: { remaining?: number; total?: number },
note = '',
) {
return portalFetch<{
ok: boolean;
unchanged?: boolean;
subscription: AdminSubscription;
quota: ImageQuotaView;
}>(`/admin-api/users/${userId}/image-quota`, {
method: 'PUT',
body: JSON.stringify({ ...payload, note }),
});
}
export async function grantUserImageQuota(userId: string, delta: number, note = '') {
return portalFetch<{
ok: boolean;
subscription: AdminSubscription;
quota: ImageQuotaView;
}>(`/admin-api/users/${userId}/image-quota/grant`, {
method: 'POST',
body: JSON.stringify({ delta, note }),
});
}
export async function fetchImageQuotaLedger(params: {
userId?: string;
page?: number;
pageSize?: number;
} = {}) {
const q = new URLSearchParams();
if (params.userId) q.set('userId', params.userId);
if (params.page) q.set('page', String(params.page));
if (params.pageSize) q.set('pageSize', String(params.pageSize));
return portalFetch<{
entries: ImageQuotaLedgerEntry[];
total: number;
page: number;
pageSize: number;
totalPages: number;
}>(`/admin-api/image-quota/ledger${q.toString() ? `?${q}` : ''}`);
}
+251
View File
@@ -0,0 +1,251 @@
import { useMemo } from 'react';
import {
Bar,
CartesianGrid,
ComposedChart,
Legend,
Line,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import type { UsageStatsBucket } from '../types';
import { formatYuan } from '../admin/utils/format';
export type UsageChartMetric = 'cost' | 'tokens' | 'count';
export type UsageChartType = 'bar' | 'line';
export const METRIC_OPTIONS: { key: UsageChartMetric; label: string }[] = [
{ key: 'tokens', label: 'Token 总量' },
{ key: 'cost', label: '扣费金额' },
{ key: 'count', label: '请求次数' },
];
export const METRIC_CONFIG: Record<
UsageChartMetric,
{ label: string; color: string; yAxisId: 'left' | 'right' }
> = {
tokens: { label: 'Token 总量', color: '#3d8bfd', yAxisId: 'left' },
cost: { label: '扣费金额', color: '#22c55e', yAxisId: 'right' },
count: { label: '请求次数', color: '#f59e0b', yAxisId: 'right' },
};
export const DEFAULT_CHART_METRICS: UsageChartMetric[] = ['tokens'];
function formatDayLabel(day: string) {
const [, month, date] = day.split('-');
return `${Number(month)}/${Number(date)}`;
}
function fillDailyBuckets(buckets: UsageStatsBucket[], startAt: number, endAt: number) {
const map = new Map(buckets.map((b) => [b.day, b]));
const start = new Date(startAt * 1000);
start.setHours(0, 0, 0, 0);
const end = new Date(endAt * 1000);
end.setHours(0, 0, 0, 0);
const filled: UsageStatsBucket[] = [];
for (let cursor = new Date(start); cursor <= end; cursor.setDate(cursor.getDate() + 1)) {
const y = cursor.getFullYear();
const m = String(cursor.getMonth() + 1).padStart(2, '0');
const d = String(cursor.getDate()).padStart(2, '0');
const day = `${y}-${m}-${d}`;
filled.push(
map.get(day) ?? {
day,
count: 0,
inputTokens: 0,
outputTokens: 0,
costCents: 0,
},
);
}
return filled;
}
function formatMetricValue(value: number, metric: UsageChartMetric) {
if (metric === 'cost') return `¥${formatYuan(Math.round(value * 100))}`;
return value.toLocaleString();
}
type ChartPoint = {
day: string;
label: string;
tokens: number;
cost: number;
count: number;
inputTokens: number;
outputTokens: number;
costCents: number;
};
function UsageTooltip({
active,
payload,
metrics,
}: {
active?: boolean;
payload?: Array<{ payload: ChartPoint; dataKey?: string; color?: string }>;
metrics: UsageChartMetric[];
}) {
if (!active || !payload?.length) return null;
const row = payload[0].payload;
return (
<div className="usage-chart-tooltip">
<div className="usage-chart-tooltip-title">{row.day}</div>
{metrics.map((metric) => (
<div key={metric} className="usage-chart-tooltip-metric">
<span className="usage-chart-tooltip-dot" style={{ background: METRIC_CONFIG[metric].color }} />
{METRIC_CONFIG[metric].label}:{formatMetricValue(row[metric], metric)}
</div>
))}
<div className="muted usage-chart-tooltip-detail">
入 {row.inputTokens.toLocaleString()} / 出 {row.outputTokens.toLocaleString()} Token
</div>
</div>
);
}
export function UsageTrendChart({
buckets,
startAt,
endAt,
metrics,
chartType,
}: {
buckets: UsageStatsBucket[];
startAt: number;
endAt: number;
metrics: UsageChartMetric[];
chartType: UsageChartType;
}) {
const activeMetrics = metrics.length > 0 ? metrics : DEFAULT_CHART_METRICS;
const data = useMemo(() => {
const filled = fillDailyBuckets(buckets, startAt, endAt);
return filled.map((bucket) => ({
day: bucket.day,
label: formatDayLabel(bucket.day),
tokens: bucket.inputTokens + bucket.outputTokens,
cost: bucket.costCents / 100,
count: bucket.count,
inputTokens: bucket.inputTokens,
outputTokens: bucket.outputTokens,
costCents: bucket.costCents,
}));
}, [buckets, startAt, endAt]);
const hasData = data.some((row) => activeMetrics.some((metric) => row[metric] > 0));
const showLeftAxis = activeMetrics.includes('tokens');
const showRightAxis = activeMetrics.some((m) => m === 'cost' || m === 'count');
const resolveYAxisId = (metric: UsageChartMetric): 'left' | 'right' => {
if (showLeftAxis && showRightAxis) return METRIC_CONFIG[metric].yAxisId;
if (showLeftAxis) return 'left';
return 'right';
};
if (!hasData) {
return <p className="muted usage-chart-empty">所选时间范围内暂无用量数据</p>;
}
return (
<div className="usage-chart-wrap">
<ResponsiveContainer width="100%" height={300}>
<ComposedChart data={data} margin={{ top: 8, right: showRightAxis ? 16 : 8, left: 0, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border-subtle)" />
<XAxis
dataKey="label"
tick={{ fontSize: 11, fill: 'var(--color-text-muted)' }}
interval={data.length > 14 ? Math.floor(data.length / 7) : 0}
/>
{showLeftAxis && (
<YAxis
yAxisId="left"
tick={{ fontSize: 11, fill: METRIC_CONFIG.tokens.color }}
tickFormatter={(v) => (v >= 10000 ? `${(v / 10000).toFixed(0)}万` : String(v))}
width={52}
/>
)}
{showRightAxis && (
<YAxis
yAxisId="right"
orientation="right"
tick={{ fontSize: 11, fill: 'var(--color-text-muted)' }}
tickFormatter={(v) => (Number.isInteger(v) ? String(v) : v.toFixed(2))}
width={48}
/>
)}
<Tooltip content={<UsageTooltip metrics={activeMetrics} />} />
<Legend
wrapperStyle={{ fontSize: 12, paddingTop: 8 }}
formatter={(value) => <span style={{ color: 'var(--color-text-muted)' }}>{value}</span>}
/>
{activeMetrics.map((metric) => {
const cfg = METRIC_CONFIG[metric];
const axisId = resolveYAxisId(metric);
if (chartType === 'bar') {
return (
<Bar
key={metric}
yAxisId={axisId}
dataKey={metric}
name={cfg.label}
fill={cfg.color}
radius={[4, 4, 0, 0]}
maxBarSize={activeMetrics.length > 1 ? 24 : 40}
/>
);
}
return (
<Line
key={metric}
yAxisId={axisId}
type="monotone"
dataKey={metric}
name={cfg.label}
stroke={cfg.color}
strokeWidth={2}
dot={{ r: 3, fill: cfg.color }}
activeDot={{ r: 5 }}
/>
);
})}
</ComposedChart>
</ResponsiveContainer>
</div>
);
}
export function toggleChartMetric(current: UsageChartMetric[], metric: UsageChartMetric): UsageChartMetric[] {
if (current.includes(metric)) {
if (current.length === 1) return current;
return current.filter((m) => m !== metric);
}
return [...current, metric];
}
export function dateRangeToUnix(startDate: string, endDate: string) {
const [sy, sm, sd] = startDate.split('-').map(Number);
const [ey, em, ed] = endDate.split('-').map(Number);
const startAt = Math.floor(new Date(sy, sm - 1, sd, 0, 0, 0, 0).getTime() / 1000);
const endAt = Math.floor(new Date(ey, em - 1, ed, 23, 59, 59, 999).getTime() / 1000);
return { startAt, endAt };
}
export function formatDateInput(date: Date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
export function presetDateRange(days: number) {
const end = new Date();
end.setHours(0, 0, 0, 0);
const start = new Date(end);
start.setDate(start.getDate() - (days - 1));
return { startDate: formatDateInput(start), endDate: formatDateInput(end) };
}
+596
View File
@@ -446,6 +446,212 @@ body,
margin-bottom: 16px;
}
/* ── Workflow Orchestrator ─────────────────────────── */
.orchestrator-page {
display: grid;
gap: 16px;
}
.orchestrator-page .admin-card {
margin-bottom: 0;
}
.orchestrator-page h2 {
margin: 0 0 4px;
}
.orchestrator-summary,
.orchestrator-executors,
.orchestrator-metrics {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
}
.orchestrator-summary > div,
.orchestrator-metrics > div,
.orchestrator-executors article {
display: grid;
gap: 5px;
padding: 12px;
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
background: var(--color-bg-elevated);
}
.orchestrator-summary span,
.orchestrator-metrics span {
color: var(--color-text-muted);
font-size: 12px;
}
.orchestrator-state,
.orchestrator-readiness {
margin: 14px 0 0;
padding: 12px;
border: 1px solid rgba(224, 175, 91, 0.35);
border-radius: var(--radius-md);
background: rgba(224, 175, 91, 0.08);
}
.orchestrator-state.danger {
border-color: rgba(224, 86, 86, 0.4);
background: rgba(224, 86, 86, 0.08);
}
.orchestrator-section-head,
.orchestrator-executors article > div,
.orchestrator-readiness > div,
.orchestrator-health {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.orchestrator-executors article p {
margin: 0;
color: var(--color-text-muted);
font-size: 12px;
}
.orchestrator-executors article span {
color: var(--color-warning);
font-size: 12px;
}
.orchestrator-readiness.ready {
border-color: rgba(70, 176, 120, 0.4);
background: rgba(70, 176, 120, 0.08);
}
.orchestrator-readiness p {
margin: 10px 0;
}
.orchestrator-checks {
display: grid !important;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
align-items: start !important;
justify-content: stretch !important;
gap: 6px !important;
}
.orchestrator-checks span {
font-size: 12px;
}
.orchestrator-checks .passed {
color: var(--color-success);
}
.orchestrator-checks .blocked {
color: var(--color-warning);
}
.orchestrator-metrics {
margin: 14px 0;
}
.orchestrator-table small,
.admin-table td small {
display: block;
color: var(--color-text-muted);
margin-top: 4px;
}
.orchestrator-detail {
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--color-border);
}
.orchestrator-detail > div:last-child {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 12px;
}
.orchestrator-detail pre {
max-height: 320px;
overflow: auto;
padding: 12px;
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
background: var(--color-bg-elevated);
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 11px;
}
.orchestrator-form-grid,
.orchestrator-allowlists {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.orchestrator-form-grid label,
.orchestrator-allowlists label {
display: grid;
gap: 6px;
color: var(--color-text-muted);
font-size: 12px;
}
.orchestrator-form-grid .wide {
grid-column: 1 / -1;
}
.orchestrator-health {
margin: 14px 0;
padding: 10px 12px;
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
}
.orchestrator-toggles {
display: grid;
gap: 10px;
margin-bottom: 14px;
}
.orchestrator-toggles label {
display: flex;
align-items: center;
gap: 8px;
}
.orchestrator-toggles input {
width: auto;
}
.orchestrator-toggles .handoff {
padding: 10px;
border: 1px solid rgba(224, 175, 91, 0.35);
border-radius: var(--radius-md);
background: rgba(224, 175, 91, 0.08);
}
.orchestrator-actions {
justify-content: flex-end;
margin-top: 14px;
}
@media (max-width: 720px) {
.orchestrator-form-grid,
.orchestrator-allowlists {
grid-template-columns: 1fr;
}
.orchestrator-section-head,
.orchestrator-health {
align-items: flex-start;
flex-direction: column;
}
}
.providers-page {
display: grid;
gap: 14px;
@@ -577,6 +783,51 @@ body,
justify-self: stretch;
}
.search-service-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr));
gap: 14px;
margin: 14px 0;
}
.search-service-card {
min-width: 0;
padding: 14px;
border: 1px solid var(--color-border-input);
border-radius: var(--radius-md);
}
.search-service-card legend {
padding: 0 6px;
font-weight: 600;
}
.search-service-toggle {
display: flex !important;
align-items: center;
gap: 8px;
margin-bottom: 12px;
color: var(--color-text-primary) !important;
}
.search-service-toggle input {
width: auto;
margin: 0;
}
.search-service-actions {
display: flex;
gap: 8px;
margin-top: 12px;
}
.search-llm-hint {
margin: -2px 0 0;
color: var(--color-text-muted);
font-size: 12px;
line-height: 1.55;
}
.form-span-all {
grid-column: 1 / -1;
}
@@ -1080,6 +1331,60 @@ body,
min-width: 0;
}
.asset-image-make-note,
.asset-no-llm {
padding: 9px 10px;
border-radius: var(--radius-sm);
background: rgba(132, 110, 255, .1);
color: var(--color-text-muted);
font-size: 11px;
line-height: 1.5;
}
.asset-purpose-fieldset {
min-width: 0;
margin: 2px 0 0;
padding: 10px;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
}
.asset-purpose-fieldset legend {
padding: 0 5px;
color: var(--color-text-muted);
font-size: 11px;
}
.asset-purpose-fieldset > p {
margin: 8px 0 0;
color: var(--color-text-muted);
font-size: 10px;
line-height: 1.45;
}
.asset-purpose-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 7px;
}
.asset-purpose-grid label {
display: flex;
align-items: flex-start;
gap: 7px;
padding: 7px;
border-radius: var(--radius-xs);
background: rgba(255, 255, 255, .035);
}
.asset-purpose-grid small {
display: block;
margin-top: 2px;
color: var(--color-text-muted);
font-size: 9px;
word-break: break-all;
}
.asset-plugin-footer {
display: flex;
align-items: center;
@@ -1792,6 +2097,297 @@ body,
text-align: center;
}
.usage-toolbar {
flex-wrap: wrap;
}
.usage-tab-head {
flex-wrap: wrap;
gap: 12px;
}
.usage-view-switch {
display: inline-flex;
border: 1px solid var(--color-border-input);
border-radius: var(--radius-md);
overflow: hidden;
}
.usage-view-btn {
padding: 6px 14px;
font-size: 13px;
border: none;
background: var(--color-bg-base);
color: var(--color-text-muted);
cursor: pointer;
}
.usage-view-btn.active {
background: var(--color-accent);
color: #fff;
}
.usage-tab-body {
margin-top: 4px;
}
.usage-query-toolbar {
margin-bottom: 16px;
}
.usage-user-balance-bar {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 8px 16px;
margin-bottom: 16px;
padding: 12px 16px;
border: 1px solid var(--color-border-subtle);
border-radius: var(--radius-md);
background: var(--color-bg-subtle);
}
.usage-user-balance-name {
font-weight: 600;
margin-right: auto;
}
.usage-user-balance-value {
font-size: 20px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.usage-summary-panel {
display: flex;
flex-direction: column;
gap: 16px;
margin-bottom: 16px;
}
.usage-summary-block {
padding: 14px 16px;
border: 1px solid var(--color-border-subtle);
border-radius: var(--radius-md);
background: var(--color-bg-subtle);
}
.usage-summary-title {
margin: 0 0 10px;
font-size: 13px;
font-weight: 600;
}
.usage-summary-grid {
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
}
.usage-summary-grid .admin-stat-card {
padding: 10px 12px;
}
.usage-summary-grid .admin-stat-value {
font-size: 20px;
}
.usage-summary-sub {
margin-top: 4px;
font-size: 11px;
}
.usage-summary-loading {
margin-bottom: 12px;
}
.usage-overview-filter,
.usage-overview-chart-bar {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
flex-wrap: wrap;
}
.usage-overview-chart-label {
font-size: 13px;
}
.usage-chart-hint {
margin: 4px 0 0;
font-size: 12px;
}
.usage-preset-btn.active {
background: var(--color-accent);
border-color: var(--color-accent);
color: #fff;
}
.usage-date-range {
display: flex;
align-items: center;
gap: 6px;
}
.usage-date-input {
width: 138px;
}
.usage-date-sep {
font-size: 12px;
}
.usage-preset-btns {
display: flex;
gap: 4px;
}
.usage-preset-btn {
padding: 5px 10px;
font-size: 12px;
min-width: unset;
}
.usage-chart-panel {
margin: 16px 0 20px;
padding: 16px;
border: 1px solid var(--color-border-subtle);
border-radius: var(--radius-md);
background: var(--color-bg-subtle);
}
.usage-chart-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
flex-wrap: wrap;
}
.usage-chart-head h3 {
margin: 0;
font-size: 14px;
font-weight: 600;
}
.usage-chart-controls {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.usage-metric-checks {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.usage-metric-check {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 10px;
border: 1px solid var(--color-border-input);
border-radius: var(--radius-md);
font-size: 12px;
cursor: pointer;
user-select: none;
background: var(--color-bg-base);
color: var(--color-text-muted);
}
.usage-metric-check.checked {
border-color: var(--color-border-subtle);
color: var(--color-text-primary);
}
.usage-metric-check input {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
.usage-metric-check-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
}
.usage-chart-tooltip-metric {
display: flex;
align-items: center;
gap: 6px;
margin-top: 2px;
}
.usage-chart-tooltip-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
}
.usage-chart-tooltip-detail {
margin-top: 6px;
font-size: 11px;
}
.usage-chart-select {
min-width: 120px;
padding: 5px 8px;
font-size: 12px;
}
.usage-chart-type-toggle {
display: inline-flex;
border: 1px solid var(--color-border-input);
border-radius: var(--radius-md);
overflow: hidden;
}
.usage-chart-type-btn {
padding: 5px 12px;
font-size: 12px;
border: none;
background: var(--color-bg-base);
color: var(--color-text-muted);
cursor: pointer;
}
.usage-chart-type-btn.active {
background: var(--color-accent);
color: #fff;
}
.usage-chart-wrap {
width: 100%;
}
.usage-chart-empty {
padding: 40px 0;
text-align: center;
}
.usage-chart-tooltip {
padding: 8px 10px;
border-radius: var(--radius-md);
background: var(--color-bg-base);
border: 1px solid var(--color-border-subtle);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
font-size: 12px;
line-height: 1.5;
}
.usage-chart-tooltip-title {
font-weight: 600;
margin-bottom: 4px;
}
.text-income {
color: #22c55e;
}
+154
View File
@@ -208,6 +208,12 @@ export type AssetPluginConfig = {
llmProviderId: string | null;
llmModel: string | null;
updatedAt: number | null;
purposes?: Record<string, boolean>;
purposeCatalog?: Array<{
id: string;
label: string;
presetId: string;
}>;
};
export type AssetGatewayConfig = {
@@ -231,6 +237,7 @@ export type UsageRecord = {
id: number;
userId: string;
username: string;
displayName: string;
agentSessionId: string;
requestId: string | null;
inputTokens: number;
@@ -240,10 +247,42 @@ export type UsageRecord = {
createdAt: number;
};
export type UsageStatsBucket = {
day: string;
count: number;
inputTokens: number;
outputTokens: number;
costCents: number;
};
export type UsageTotals = {
count: number;
inputTokens: number;
outputTokens: number;
costCents: number;
};
export type UsageRangeTotals = UsageTotals & {
startAt: number;
endAt: number;
};
export type UsageSummaryResult = {
range: UsageRangeTotals | null;
allTime: UsageTotals;
};
export type UsageStatsResult = {
buckets: UsageStatsBucket[];
startAt: number;
endAt: number;
};
export type LedgerEntry = {
id: number;
userId: string;
username: string;
displayName: string;
type: 'recharge' | 'deduct' | 'refund' | 'adjust';
amountCents: number;
tokens: number;
@@ -279,6 +318,31 @@ export type WechatScheduleLlmConfig = {
updatedBy: string | null;
};
export type WechatIntentRouterAdminConfig = {
enabled: boolean;
shadowMode: boolean;
modelProviderKeyId: string | null;
model: string | null;
minConfidence: number;
timeoutMs: number;
canaryOpenids: string[];
updatedAt?: number | null;
updatedBy?: string | null;
};
export type WechatIntentRouterConfigState = {
config: WechatIntentRouterAdminConfig;
};
export type WechatIntentRouterRuntimeState = {
source: string;
updatedAt: number | null;
updatedBy: string | null;
fingerprint?: string;
overrides: Record<string, string>;
config: WechatIntentRouterAdminConfig;
};
export type MindSpaceAdminConfig = {
publicPageLimit: number;
analytics: {
@@ -336,6 +400,14 @@ export type MemoryV2AdminConfigResponse = {
updatedBy: string | null;
};
export type MemoryV2ConfigRuntimeState = {
source: string;
updatedAt: number | null;
updatedBy: string | null;
fingerprint?: string;
overrides: Record<string, string>;
};
export type MemoryV2RuntimeStatusResponse = {
ok: boolean;
checkedAt?: number;
@@ -574,6 +646,27 @@ export type BlockedWord = {
updated_at: number;
};
export type BillingAdminConfig = {
useBackendCost: boolean;
usdCnyRate: number;
marginMultiplier: number;
inputCentsPer1k: number;
outputCentsPer1k: number;
minBillCents: number;
costEstimateFromTokens: boolean;
costEstimateInputUsdPer1M: number;
costEstimateOutputUsdPer1M: number;
};
export type BillingAdminConfigResponse = {
config: BillingAdminConfig;
updatedAt: number | null;
updatedBy: string | null;
source?: string;
envOverrideActive?: boolean;
formula?: string;
};
export type PlanDefinition = {
planType: string;
name: string;
@@ -610,6 +703,32 @@ export type AdminSubscription = {
periodTokensUsed: number;
periodImagesLimit: number;
periodImagesUsed: number;
periodImagesBonus?: number;
note: string | null;
createdAt: number;
};
export type ImageQuotaView = {
limit: number;
bonus: number;
used: number;
total: number | null;
remaining: number | null;
unlimited: boolean;
periodEnd: number | null;
planType: string | null;
};
export type ImageQuotaLedgerEntry = {
id: string;
userId: string;
username?: string;
displayName?: string;
delta: number;
balanceAfter: number | null;
reason: string;
refId: string | null;
operatorId: string | null;
note: string | null;
createdAt: number;
};
@@ -619,4 +738,39 @@ export type MindSearchConfig = {
mode: 'off' | 'shadow' | 'assist';
providers: { searxng: boolean; github: boolean; reader: boolean };
settings: { searxngEndpoint: string; maxResults: number; timeoutMs: number; readerMaxChars: number };
services: MindSearchService[];
routes: MindSearchRoutes;
};
export type MindSearchService = {
id: string;
name: string;
kind: 'provider' | 'reader' | 'orchestrator';
adapter: 'searxng' | 'github' | 'reader' | 'research-http';
capabilities: string[];
endpoint: string;
healthPath: string;
enabled: boolean;
timeoutMs: number;
priority: number;
llmProviderKeyId?: string;
llmModel?: string;
};
export type MindSearchRoutes = {
web: string;
news: string;
code: string;
read: string;
research: string;
};
export type MindSearchServiceTestResult = {
ok: boolean;
serviceId: string;
adapter: MindSearchService['adapter'];
status: number | null;
latencyMs: number;
resultCount?: number | null;
message: string;
};
+237
View File
@@ -0,0 +1,237 @@
export type OrchestratorMode = 'off' | 'shadow' | 'canary' | 'active';
export type OrchestratorConfig = {
mode: OrchestratorMode;
primaryEngine: string;
fallbackEngine: string;
serviceUrl: string;
requestTimeoutMs: number;
rolloutPercent: number;
userAllowlist: string[];
workflowAllowlist: string[];
fallbackToNative: boolean;
requireHealthy: boolean;
executionEnabled: boolean;
};
export type OrchestratorRuntime = {
killSwitch: boolean;
configured: boolean;
effective: boolean;
reason: string | null;
executesLangGraph: boolean;
plansLangGraph: boolean;
shadowsLangGraph: boolean;
executionHandoff: {
implemented: boolean;
requested: boolean;
enabled: boolean;
reason: string | null;
environmentGate: boolean;
};
};
export type OrchestratorConfigState = {
config: OrchestratorConfig;
configVersion: number;
updatedBy: string | null;
updatedAt: number | null;
source: string;
runtime: OrchestratorRuntime;
engines: Array<{
id: string;
label: string;
kind: string;
configured: boolean;
capabilities: string[];
}>;
executors: Array<{
id: string;
label: string;
kind: string;
enabled: boolean;
dispatchImplemented: boolean;
status: string;
capabilities: string[];
}>;
};
export type OrchestratorServiceHealth = {
checkedAt: number;
ok: boolean;
status: string;
latencyMs: number;
httpStatus: number | null;
details: {
service: string | null;
checkpoint: { kind?: string; durable?: boolean } | null;
execution: string | null;
executorGateway: {
dispatchImplemented: boolean;
executionEnabled: boolean;
store: { kind: string | null; durable: boolean } | null;
} | null;
} | null;
};
export type OrchestratorRuntimeState = OrchestratorConfigState & {
serviceHealth: OrchestratorServiceHealth;
};
export type OrchestratorShadowRun = {
eventId: string;
runId: string;
requestId: string;
userId: string;
sessionId: string | null;
nativeStatus: string;
nativeAttempts: number;
shadowStatus: 'succeeded' | 'failed';
engine: string;
configVersion: number | null;
phase: string | null;
taskType: string | null;
synthetic: boolean;
executorAdapter: string | null;
latencyMs: number | null;
error: { code: string; message: string } | null;
observedAt: number;
nativeCompletedAt: number | null;
};
export type OrchestratorShadowRunList = {
generatedAt: number;
window: { hours: number; from: number };
metrics: {
observations: number;
successes: number;
failures: number;
successRate: number | null;
failureRate: number | null;
latencyP50Ms: number | null;
latencyP95Ms: number | null;
nativeSucceeded: number;
nativeFailed: number;
lastObservedAt: number | null;
sampled: boolean;
};
runs: OrchestratorShadowRun[];
};
export type OrchestratorExecutionPlanList = {
generatedAt: number;
window: { hours: number; from: number };
metrics: {
decisions: number;
candidateSelections: number;
candidateSelectionRate: number | null;
nativeSelections: number;
nativeSucceeded: number;
nativeFailed: number;
nativeSettledRate: number | null;
handoffAllowed: number;
distinctSessions: number;
lastPlannedAt: number | null;
candidateReasons: Array<{ value: string; count: number }>;
taskTypes: Array<{ value: string; count: number }>;
sampled: boolean;
};
plans: Array<{
eventId: string;
runId: string;
requestId: string;
userId: string;
sessionId: string | null;
nativeStatus: string;
nativeAttempts: number;
mode: string | null;
candidateEngine: string;
effectiveEngine: string;
fallbackEngine: string;
reason: string | null;
candidateReason: string | null;
configVersion: number | null;
bucket: number | null;
taskType: string | null;
dryRun: boolean;
handoffAllowed: boolean;
plannedAt: number;
nativeCompletedAt: number | null;
}>;
};
export type OrchestratorCanaryReadinessCheck = {
id: string;
passed: boolean;
actual: string | number | boolean | null;
target: string | number | boolean | null;
};
export type OrchestratorCanaryReadiness = {
generatedAt: number;
ready: boolean;
recommendation: 'keep_shadow' | 'manual_canary_review';
window: { hours: number; from: number };
thresholds: {
hours: number;
minObservations: number;
minSuccessRate: number;
maxP95LatencyMs: number;
minLatencyCoverageRate: number;
minNativeSettledRate: number;
minDistinctSessions: number;
maxHoursSinceLastObservation: number;
};
samples: {
totalObservations: number;
eligibleObservations: number;
excludedSynthetic: number;
successes: number;
failures: number;
successRate: number | null;
latencyCoverageRate: number | null;
latencyP95Ms: number | null;
nativeSettledRate: number | null;
distinctSessions: number;
lastObservedAt: number | null;
hoursSinceLastObservation: number | null;
sampled: boolean;
};
service: {
status: string | null;
latencyMs: number | null;
checkpointKind: string | null;
checkpointDurable: boolean | null;
executorJobStoreKind: string | null;
executorJobStoreDurable: boolean | null;
execution: string | null;
};
checks: OrchestratorCanaryReadinessCheck[];
blockers: string[];
failureCodes: Array<{ code: string; count: number }>;
};
export type OrchestratorShadowRunDetail = {
native: {
runId: string;
requestId: string;
userId: string;
sessionId: string | null;
status: string;
attempts: number;
completedAt: number | null;
};
shadow: OrchestratorShadowRun | null;
remote: {
available: boolean;
state: Record<string, unknown> | null;
events: Array<Record<string, unknown>>;
error: { code: string; message: string } | null;
executorJob: {
available: boolean;
state: Record<string, unknown> | null;
events: Array<Record<string, unknown>>;
error: { code: string; message: string } | null;
};
};
};