Compare commits

..

4 Commits

Author SHA1 Message Date
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
14 changed files with 1086 additions and 7 deletions
+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 | 业务逻辑与 PortalUI 不在此仓库 |
新增管理功能时:在本仓库添加 `src/admin/pages/*`、更新 `AdminNav.tsx``App.tsx`;若需新 API,在 `server/app.mjs` 挂载并复用 Memind 模块。Memind 侧仅实现共享业务,不在 `ops/` 做 UI。
+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);
});
+80
View File
@@ -1183,6 +1183,86 @@ 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.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) {
+1
View File
@@ -159,6 +159,7 @@ export async function bootstrapAdminServices() {
const subscriptionService = createSubscriptionService(pool, {
getPlanAsync: (planType) => planCatalogService.getPlan(planType),
});
subscriptionService._planCatalogService = planCatalogService;
await ensureSystemTestAccountSchema(pool);
const systemTestAccountService = createSystemTestAccountService(pool);
+3
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';
@@ -119,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 />} />
@@ -170,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')
+4 -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: '平台配置',
+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"
+80 -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, grantUserImageQuota } 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,9 @@ 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 [imageGrant, setImageGrant] = useState({ delta: '', note: '' });
useEffect(() => {
if (!user?.spaceQuotaBytes) return;
@@ -57,6 +60,28 @@ 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]);
const handleRecharge = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
@@ -75,6 +100,33 @@ export function UserDetailPage() {
}
};
const handleImageGrant = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
setMessage(null);
setLocalError(null);
setError(null);
const delta = Math.floor(Number(imageGrant.delta));
if (!Number.isFinite(delta) || delta === 0) {
setLocalError('请输入非零整数额度');
return;
}
try {
const result = await grantUserImageQuota(user.id, delta, imageGrant.note.trim());
setImageQuota(result.quota);
setMessage('图片额度已更新');
setImageGrant({ delta: '', note: '' });
} 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 +238,32 @@ export function UserDetailPage() {
</form>
</section>
<section className="admin-card">
<h2></h2>
{imageQuotaLoading ? (
<p className="muted"></p>
) : (
<p className="muted">{imageQuotaSummary || '暂无额度信息(用户可能尚无订阅)'}</p>
)}
<form className="admin-form" onSubmit={handleImageGrant}>
<input
placeholder="调整额度(张,正数充值、负数扣减)"
type="number"
step="1"
value={imageGrant.delta}
onChange={(e) => setImageGrant((s) => ({ ...s, delta: e.target.value }))}
/>
<input
placeholder="备注"
value={imageGrant.note}
onChange={(e) => setImageGrant((s) => ({ ...s, note: e.target.value }))}
/>
<button type="submit" className="send-btn">
</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);
}
+72
View File
@@ -12,6 +12,8 @@ import type {
CapabilityDefinition,
CapabilityMap,
InsufficientBalanceDetails,
ImageQuotaLedgerEntry,
ImageQuotaView,
LedgerEntry,
LlmConnectionTestResult,
LlmExecutorBinding,
@@ -51,6 +53,9 @@ import type {
WechatDeliveryLog,
WechatDigestSubscription,
WechatScheduleLlmConfig,
WechatIntentRouterAdminConfig,
WechatIntentRouterConfigState,
WechatIntentRouterRuntimeState,
WechatMessage,
WechatWebNotification,
MindSearchConfig,
@@ -446,6 +451,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');
}
@@ -1329,3 +1353,51 @@ 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 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}` : ''}`);
}
+51
View File
@@ -317,6 +317,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: {
@@ -656,6 +681,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;
};