Commit 192031cf by imwangxiaozhou

feat(agent-admin): 初始化运维控制台前端并新增多组后端业务功能

- 初始化完整 React + TypeScript + Vite 运维控制台前端项目,包含主题切换、侧边导航与各业务页面
- 封装前端API调用层,对接后端新增的所有业务接口
- 新增管家Agent支持:添加`is_steward`字段、实现唯一校验逻辑与存在检查接口
- 新增技能管理功能:支持上传zip包创建技能、扫描本地`skills/`目录同步未入库技能
- 新增客户群管理全套接口:包含列表、聊天记录查询与统计分析能力
- 新增企业微信机器人二维码状态查询接口
- 优化`meeting_minutes`技能的SKILL.md格式,清理多余空行
1 parent f7187185
Showing 32 changed files with 1655 additions and 8 deletions
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.model.wecom_sync import WeComBot
from app.model.agent_group import WeComEmployeeQrcode
from app.schema.common import ApiResponse, success_response_payload from app.schema.common import ApiResponse, success_response_payload
from app.schema.agent_group import ( from app.schema.agent_group import (
EmployeeMountsResponse, EmployeeMountsResponse,
...@@ -17,6 +20,24 @@ from app.service.agent_group_helper_service import ( ...@@ -17,6 +20,24 @@ from app.service.agent_group_helper_service import (
WeComUnavailableError, WeComUnavailableError,
) )
class BotQrcodeItem(BaseModel):
bot_id: str
bot_name: str
channel: str
corp_name: str | None = None
online: bool | None = None
status: str | None = None
queue_count: int | None = None
pending_count: int | None = None
has_qrcode: bool
qrcode_url: str | None = None
class BotQrcodeListResponse(BaseModel):
total: int
bots: list[BotQrcodeItem]
router = APIRouter(prefix="/api/v1/agent-group") router = APIRouter(prefix="/api/v1/agent-group")
...@@ -25,6 +46,43 @@ def get_wecom_client(): ...@@ -25,6 +46,43 @@ def get_wecom_client():
@router.get( @router.get(
"/bots",
response_model=ApiResponse[BotQrcodeListResponse],
summary="获取所有机器人及其二维码状态",
)
def list_bots_qrcode(db: Session = Depends(get_db)):
bots = db.query(WeComBot).order_by(WeComBot.id.asc()).all()
qrcode_rows = db.query(WeComEmployeeQrcode).all()
qrcode_url_map: dict[str, str] = {}
qrcode_employee_ids: set[str] = set()
for row in qrcode_rows:
if row.employee_id and str(row.qrcode_url or "").strip():
qrcode_employee_ids.add(row.employee_id)
qrcode_url_map[row.employee_id] = row.qrcode_url
items = [
BotQrcodeItem(
bot_id=str(bot.bot_id or ""),
bot_name=bot.bot_name or "",
channel=str(bot.channel or ""),
corp_name=str(bot.corp_name) if bot.corp_name else None,
online=bot.online if bot.online is not None else None,
status=str(bot.status) if bot.status else None,
queue_count=bot.queue_count,
pending_count=bot.pending_count,
has_qrcode=str(bot.bot_id or "") in qrcode_employee_ids,
qrcode_url=qrcode_url_map.get(str(bot.bot_id or "")),
)
for bot in bots
if bot.bot_id
]
return success_response_payload(
200,
BotQrcodeListResponse(total=len(items), bots=items).model_dump(mode="json"),
)
@router.get(
"/position/{position_code}/employees", "/position/{position_code}/employees",
response_model=ApiResponse[PositionEmployeesResponse], response_model=ApiResponse[PositionEmployeesResponse],
) )
......
...@@ -27,6 +27,16 @@ from app.service.agent_service import AgentService ...@@ -27,6 +27,16 @@ from app.service.agent_service import AgentService
router = APIRouter(prefix="/api/v1/agents") router = APIRouter(prefix="/api/v1/agents")
@router.get("/steward/check", response_model=ApiResponse, summary="检查管家 Agent 是否存在")
def check_steward_exists(db: Session = Depends(get_db)):
svc = AgentService(db)
steward = svc.find_steward()
return success_response_payload(
200,
{"exists": steward is not None, "agent_id": steward.id if steward else None, "name": steward.name if steward else None},
)
def _managed_user_bot_id(agent) -> Optional[str]: def _managed_user_bot_id(agent) -> Optional[str]:
if agent.managed_user_id is None: if agent.managed_user_id is None:
return None return None
......
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File, Form
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.schema.common import ApiResponse, success_response_payload from app.schema.common import ApiResponse, success_response_payload
from app.schema.skill import SkillCreateRequest, SkillListResponse, SkillDetailResponse from app.schema.skill import SkillCreateRequest, SkillListResponse, SkillDetailResponse, ScanSkillsResponse, ScanSkillResult
from app.service.skill_service import SkillService from app.service.skill_service import SkillService
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.infrastructure.cache import InMemorySkillCache, SkillCache from app.infrastructure.cache import InMemorySkillCache, SkillCache
...@@ -50,4 +50,65 @@ def get_skill_detail(skill_code: str, db: Session = Depends(get_db), cache: Skil ...@@ -50,4 +50,65 @@ def get_skill_detail(skill_code: str, db: Session = Depends(get_db), cache: Skil
@router.post("", response_model=ApiResponse[SkillDetailResponse], status_code=201) @router.post("", response_model=ApiResponse[SkillDetailResponse], status_code=201)
def create_skill(req: SkillCreateRequest, db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)): def create_skill(req: SkillCreateRequest, db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)):
svc = SkillService(db, cache) svc = SkillService(db, cache)
try:
return success_response_payload(201, svc.create_skill(req).model_dump(mode="json")) return success_response_payload(201, svc.create_skill(req).model_dump(mode="json"))
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.post("/upload", response_model=ApiResponse[SkillDetailResponse], status_code=201)
def upload_skill_zip(
file: UploadFile = File(...),
skill_name: str = Form(""),
priority: int = Form(1),
db: Session = Depends(get_db),
cache: SkillCache = Depends(get_cache),
):
"""上传 zip 包创建 Skill。zip 需要包含一个顶层文件夹,内含 SKILL.md。
文件夹名 = skill_code,SKILL.md 的 frontmatter 中的 description 字段会被提取为 skill 描述。
"""
if not file.filename or not file.filename.endswith(".zip"):
raise HTTPException(status_code=400, detail="只支持 .zip 文件")
svc = SkillService(db, cache)
try:
# 保存 zip 到临时文件
import tempfile
with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as tmp:
content = file.file.read()
tmp.write(content)
tmp_path = tmp.name
detail = svc.create_skill_from_zip(tmp_path, skill_name=skill_name, priority=priority)
return success_response_payload(201, detail.model_dump(mode="json"))
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
finally:
import os
if "tmp_path" in locals():
try:
os.unlink(tmp_path)
except Exception:
pass
@router.post("/scan", response_model=ApiResponse[ScanSkillsResponse])
def scan_skills(db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)):
"""扫描 skills/ 目录,将磁盘上有但数据库中没有的 skill 同步到数据库。"""
svc = SkillService(db, cache)
results, imported = svc.scan_and_sync_skills()
total = len(results)
skipped = total - imported
return success_response_payload(
200,
ScanSkillsResponse(
total=total,
scanned=total,
imported=imported,
skipped=skipped,
results=results,
).model_dump(mode="json"),
)
...@@ -24,6 +24,11 @@ class AgentBase(BaseModel): ...@@ -24,6 +24,11 @@ class AgentBase(BaseModel):
class AgentCreate(AgentBase): class AgentCreate(AgentBase):
position_ids: List[int] = Field(..., description="关联岗位 ID 列表", examples=[[1, 3]]) position_ids: List[int] = Field(..., description="关联岗位 ID 列表", examples=[[1, 3]])
skill_codes: List[str] = Field(..., description="关联技能编码列表", examples=[["query-metric", "query-detail"]]) skill_codes: List[str] = Field(..., description="关联技能编码列表", examples=[["query-metric", "query-detail"]])
is_steward: bool = Field(
default=False,
description="是否为管家 Agent,不传则默认为 False",
examples=[False],
)
managed_user_id: str = Field( managed_user_id: str = Field(
..., ...,
description="托管员工 bot_id。接口这里传的是 wecom_bots.bot_id,服务端会先解析成 wecom_bots.id 后再写入 ai_agents.managed_user_id。", description="托管员工 bot_id。接口这里传的是 wecom_bots.bot_id,服务端会先解析成 wecom_bots.id 后再写入 ai_agents.managed_user_id。",
......
...@@ -28,7 +28,22 @@ class SkillDetailResponse(BaseModel): ...@@ -28,7 +28,22 @@ class SkillDetailResponse(BaseModel):
class SkillCreateRequest(BaseModel): class SkillCreateRequest(BaseModel):
skill_code: str = Field(..., min_length=1, description="Skill 编码。")
skill_name: str = Field(..., min_length=1, description="Skill 名称。") skill_name: str = Field(..., min_length=1, description="Skill 名称。")
description: Optional[str] = Field(default=None, description="Skill 简述。") description: Optional[str] = Field(default=None, description="Skill 简述。")
doc_markdown: Optional[str] = Field(default=None, description="Skill Markdown 说明。") doc_markdown: Optional[str] = Field(default=None, description="Skill Markdown 说明。")
priority: int = Field(default=1, ge=1, description="排序优先级,越小越靠前。") priority: int = Field(default=1, ge=1, description="排序优先级,越小越靠前。")
class ScanSkillResult(BaseModel):
skill_code: str
skill_name: str
status: str = Field(..., description="imported 表示已导入,skipped 表示已存在")
class ScanSkillsResponse(BaseModel):
total: int
scanned: int
imported: int
skipped: int
results: List[ScanSkillResult]
...@@ -30,12 +30,15 @@ class AgentService: ...@@ -30,12 +30,15 @@ class AgentService:
managed_user_row_id = self._resolve_managed_user_row_id(data.managed_user_id) managed_user_row_id = self._resolve_managed_user_row_id(data.managed_user_id)
self._validate_references(data.position_ids, data.skill_codes, managed_user_row_id) self._validate_references(data.position_ids, data.skill_codes, managed_user_row_id)
self._ensure_managed_user_available(managed_user_row_id) self._ensure_managed_user_available(managed_user_row_id)
if data.is_steward:
self._ensure_steward_unique()
agent = Agent( agent = Agent(
name=data.name, name=data.name,
code=self._generate_internal_code(), code=self._generate_internal_code(),
description=data.description, description=data.description,
status=data.status, status=data.status,
is_steward=data.is_steward,
managed_user_id=managed_user_row_id, managed_user_id=managed_user_row_id,
) )
self.db.add(agent) self.db.add(agent)
...@@ -219,6 +222,22 @@ class AgentService: ...@@ -219,6 +222,22 @@ class AgentService:
if occupied: if occupied:
raise ValueError(f"该员工已绑定其他Agent: [{managed_user_id}]") raise ValueError(f"该员工已绑定其他Agent: [{managed_user_id}]")
def _ensure_steward_unique(self) -> None:
existing = (
self.db.query(Agent)
.filter(Agent.is_steward == True, Agent.is_deleted == False)
.first()
)
if existing:
raise ValueError(f"管家 Agent 已存在(ID: {existing.id},名称: {existing.name}),不能重复创建")
def find_steward(self) -> Agent | None:
return (
self.db.query(Agent)
.filter(Agent.is_steward == True, Agent.is_deleted == False)
.first()
)
def _generate_internal_code(self) -> str: def _generate_internal_code(self) -> str:
for _ in range(20): for _ in range(20):
candidate = f"agent_{secrets.token_hex(6)}" candidate = f"agent_{secrets.token_hex(6)}"
......
import json import json
import re import re
import shutil
import zipfile
from pathlib import Path
from uuid import uuid4 from uuid import uuid4
from sqlalchemy import or_ from sqlalchemy import or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.model.skill import Skill from app.model.skill import Skill
from app.schema.skill import SkillCreateRequest, SkillListItem, SkillDetailResponse from app.schema.skill import SkillCreateRequest, SkillListItem, SkillDetailResponse, ScanSkillResult
from app.infrastructure.cache import SkillCache, InMemorySkillCache from app.infrastructure.cache import SkillCache, InMemorySkillCache
...@@ -13,6 +16,11 @@ class SkillService: ...@@ -13,6 +16,11 @@ class SkillService:
self.db = db self.db = db
self.cache = cache self.cache = cache
@staticmethod
def _skills_dir() -> Path:
"""backend/skills/ 目录的绝对路径。"""
return Path(__file__).resolve().parent.parent.parent / "skills"
def list_skills(self, page: int = 1, page_size: int = 20, keyword: str | None = None) -> tuple[int, list[SkillListItem]]: def list_skills(self, page: int = 1, page_size: int = 20, keyword: str | None = None) -> tuple[int, list[SkillListItem]]:
query = self.db.query(Skill) query = self.db.query(Skill)
if keyword: if keyword:
...@@ -45,7 +53,12 @@ class SkillService: ...@@ -45,7 +53,12 @@ class SkillService:
return detail return detail
def create_skill(self, data: SkillCreateRequest) -> SkillDetailResponse: def create_skill(self, data: SkillCreateRequest) -> SkillDetailResponse:
skill_code = self._generate_skill_code(data.skill_name) skill_code = data.skill_code.strip()
if not skill_code:
raise ValueError("skill_code不能为空")
if self._skill_code_exists(skill_code):
raise ValueError("skill_code已存在")
skill = Skill( skill = Skill(
skill_code=skill_code, skill_code=skill_code,
skill_name=data.skill_name.strip(), skill_name=data.skill_name.strip(),
...@@ -60,6 +73,146 @@ class SkillService: ...@@ -60,6 +73,146 @@ class SkillService:
self.cache.set(skill.skill_code, detail.model_dump_json()) self.cache.set(skill.skill_code, detail.model_dump_json())
return detail return detail
def create_skill_from_zip(self, zip_path: str, skill_name: str, priority: int = 1) -> SkillDetailResponse:
"""解压 zip 到 skills/ 目录,解析 SKILL.md,写入数据库。"""
skills_dir = self._skills_dir()
skills_dir.mkdir(parents=True, exist_ok=True)
# 解压到临时目录,获取顶层文件夹名
temp_dir = skills_dir / f"._extract_{uuid4().hex[:8]}"
temp_dir.mkdir(parents=True, exist_ok=True)
try:
with zipfile.ZipFile(zip_path, "r") as zf:
zf.extractall(str(temp_dir))
# 找顶层子目录
entries = [e for e in temp_dir.iterdir() if e.is_dir()]
if not entries:
raise ValueError("zip 包内没有找到顶层文件夹")
if len(entries) > 1:
raise ValueError(f"zip 包根目录下只能有一个文件夹,发现了 {len(entries)} 个")
src_dir = entries[0]
skill_code = src_dir.name
# 检查 SKILL.md
skill_md_path = src_dir / "SKILL.md"
if not skill_md_path.exists():
raise ValueError(f"文件夹 {skill_code} 中没有 SKILL.md 文件")
# 解析 SKILL.md
md_content = skill_md_path.read_text(encoding="utf-8")
description = self._parse_frontmatter_field(md_content, "description")
# 从 frontmatter 取 name 作为 fallback skill_name(如果传入的为空)
effective_name = skill_name.strip() or self._parse_frontmatter_field(md_content, "name") or skill_code
# 检查 skill_code 是否已存在
if self._skill_code_exists(skill_code):
raise ValueError(f"skill_code '{skill_code}' 已存在")
# 复制到最终位置
dest_dir = skills_dir / skill_code
if dest_dir.exists():
shutil.rmtree(dest_dir)
shutil.copytree(src_dir, str(dest_dir))
# 创建数据库记录
skill = Skill(
skill_code=skill_code,
skill_name=effective_name,
description=description,
doc_markdown=md_content,
priority=priority,
)
self.db.add(skill)
self.db.commit()
self.db.refresh(skill)
detail = SkillDetailResponse.model_validate(skill)
self.cache.set(skill.skill_code, detail.model_dump_json())
return detail
finally:
# 清理临时目录
if temp_dir.exists():
shutil.rmtree(str(temp_dir))
def scan_and_sync_skills(self) -> tuple[list[ScanSkillResult], int]:
"""扫描 skills/ 目录,将磁盘上有但数据库中没有的 skill 同步到数据库。
Returns:
(results, imported_count)
"""
skills_dir = self._skills_dir()
if not skills_dir.exists():
return [], 0
results: list[ScanSkillResult] = []
for entry in sorted(skills_dir.iterdir()):
if not entry.is_dir() or entry.name.startswith("."):
continue
skill_md = entry / "SKILL.md"
if not skill_md.exists():
continue
skill_code = entry.name
if self._skill_code_exists(skill_code):
results.append(ScanSkillResult(
skill_code=skill_code,
skill_name=skill_code,
status="skipped",
))
continue
# 解析 SKILL.md
md_content = skill_md.read_text(encoding="utf-8")
description = self._parse_frontmatter_field(md_content, "description")
skill_name = self._parse_frontmatter_field(md_content, "name") or skill_code
skill = Skill(
skill_code=skill_code,
skill_name=skill_name,
description=description,
doc_markdown=md_content,
priority=999,
)
self.db.add(skill)
self.db.flush()
results.append(ScanSkillResult(
skill_code=skill_code,
skill_name=skill_name,
status="imported",
))
self.db.commit()
# 刷缓存
for result in results:
if result.status == "imported":
skill = self.db.query(Skill).filter(Skill.skill_code == result.skill_code).first()
if skill:
self.cache.set(skill.skill_code, SkillDetailResponse.model_validate(skill).model_dump_json())
imported = sum(1 for r in results if r.status == "imported")
return results, imported
@staticmethod
def _parse_frontmatter_field(md_content: str, field: str) -> str | None:
"""解析 Markdown 文件的 YAML frontmatter 中的指定字段。"""
md_content = md_content.lstrip("\ufeff")
if not md_content.startswith("---"):
return None
end = md_content.find("---", 3)
if end == -1:
return None
frontmatter = md_content[3:end].strip()
for line in frontmatter.splitlines():
# 匹配 "key: value" 格式
m = re.match(rf"^{re.escape(field)}\s*:\s*(.*?)\s*$", line)
if m:
val = m.group(1).strip().strip('"').strip("'")
return val if val else None
return None
def _generate_skill_code(self, skill_name: str) -> str: def _generate_skill_code(self, skill_name: str) -> str:
normalized = re.sub(r"[^a-z0-9]+", "_", skill_name.strip().lower()).strip("_") normalized = re.sub(r"[^a-z0-9]+", "_", skill_name.strip().lower()).strip("_")
if normalized: if normalized:
......
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>运维控制台</title>
<script>
(function() {
var theme = localStorage.getItem('theme');
if (!theme) {
theme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
}
document.documentElement.setAttribute('data-theme', theme);
})();
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
This diff could not be displayed because it is too large.
{
"name": "operation-panel",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.18.1",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/node": "^24.13.2",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.2",
"eslint": "^10.5.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.3",
"globals": "^17.6.0",
"typescript": "~6.0.2",
"typescript-eslint": "^8.61.0",
"vite": "^8.1.0"
}
}
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { Layout } from './components/Layout';
import { CreateAgent } from './pages/CreateAgent';
import { CreateBotQrcode } from './pages/CreateBotQrcode';
import { CreateSkill } from './pages/CreateSkill';
import { CustomerGroups } from './pages/CustomerGroups';
import { CustomerGroupChat } from './pages/CustomerGroupChat';
function App() {
return (
<BrowserRouter>
<Layout>
<Routes>
<Route path="/" element={<Navigate to="/customer-groups" replace />} />
<Route path="/agents/create" element={<CreateAgent />} />
<Route path="/skills/create" element={<CreateSkill />} />
<Route path="/bots/qrcode/create" element={<CreateBotQrcode />} />
<Route path="/customer-groups" element={<CustomerGroups />} />
<Route path="/customer-groups/:groupId/chat" element={<CustomerGroupChat />} />
</Routes>
</Layout>
</BrowserRouter>
);
}
export default App;
import http, { type ApiResponse } from './client';
/* ---------- Agent CRUD ---------- */
export interface CreateAgentPayload {
name: string;
description?: string;
position_ids: number[];
skill_codes: string[];
managed_user_id: string;
status?: 'enable' | 'disable';
is_steward?: boolean;
}
export interface CreateAgentResult {
agent_id: number;
name: string;
}
export async function createAgent(payload: CreateAgentPayload): Promise<CreateAgentResult> {
const res = await http.post<ApiResponse<CreateAgentResult>>('/agents', payload);
return res.data.data;
}
/* ---------- Steward Check ---------- */
export interface StewardCheckResult {
exists: boolean;
agent_id: number | null;
name: string | null;
}
export async function checkStewardExists(): Promise<StewardCheckResult> {
const res = await http.get<ApiResponse<StewardCheckResult>>('/agents/steward/check');
return res.data.data;
}
/* ---------- Position Tags ---------- */
export interface PositionTagItem {
tag_id: number;
name: string;
code: string;
agent_count: number;
description?: string | null;
created_at: string;
}
export interface PositionTagListData {
total: number;
list: PositionTagItem[];
}
export async function getPositionTags(pageSize = 100): Promise<PositionTagItem[]> {
const res = await http.get<ApiResponse<PositionTagListData>>('/position-tags', {
params: { page: 1, page_size: pageSize },
});
return res.data.data.list;
}
/* ---------- Skills ---------- */
export interface SkillItem {
skill_code: string;
skill_name: string;
description?: string | null;
}
export interface SkillListData {
total: number;
list: SkillItem[];
}
export async function getSkills(pageSize = 100): Promise<SkillItem[]> {
const res = await http.get<ApiResponse<SkillListData>>('/skills', {
params: { page: 1, page_size: pageSize },
});
return res.data.data.list;
}
/* ---------- Employee Mounts ---------- */
export interface EmployeeItem {
employee_id: string;
employee_name: string;
wechat_user_id: string;
agent_count: number;
}
export interface EmployeeMountsData {
employee_count: number;
employees: EmployeeItem[];
}
export async function getEmployeeMounts(): Promise<EmployeeItem[]> {
const res = await http.get<ApiResponse<EmployeeMountsData>>('/agent-group/employees/mounts');
return res.data.data.employees;
}
/* ---------- Bot QR Code ---------- */
export interface BotQrcodeItem {
bot_id: string;
bot_name: string;
has_qrcode: boolean;
qrcode_url: string | null;
}
export interface BotQrcodeListData {
total: number;
bots: BotQrcodeItem[];
}
export async function listBotsQrcode(): Promise<BotQrcodeItem[]> {
const res = await http.get<ApiResponse<BotQrcodeListData>>('/agent-group/bots');
return res.data.data.bots;
}
export interface UploadMediaResult {
file_url: string;
cdn_url: string;
file_type: string;
file_size: number;
width?: number | null;
height?: number | null;
}
export async function uploadMedia(file: File): Promise<UploadMediaResult> {
const form = new FormData();
form.append('usage_type', 'agent_icon');
form.append('file', file);
const res = await http.post<ApiResponse<UploadMediaResult>>('/official-site/upload', form);
return res.data.data;
}
export interface SaveQrcodeResult {
employee_id: string;
qrcode_url: string;
updated_at: string;
}
export async function saveEmployeeQrcode(employeeId: string, qrcodeUrl: string): Promise<SaveQrcodeResult> {
const res = await http.put<ApiResponse<SaveQrcodeResult>>(
`/agent-group/employee/${employeeId}/qrcode`,
{ qrcode_url: qrcodeUrl },
);
return res.data.data;
}
/* ---------- Skill ---------- */
export interface SkillDetailResult {
skill_code: string;
skill_name: string;
description?: string | null;
doc_markdown?: string | null;
}
export async function createSkill(payload: CreateSkillPayload): Promise<SkillDetailResult> {
const res = await http.post<ApiResponse<SkillDetailResult>>('/skills', payload);
return res.data.data;
}
export interface CreateSkillPayload {
skill_code: string;
skill_name: string;
description?: string;
doc_markdown?: string;
priority?: number;
}
/** 上传 zip 创建 Skill(zip 内文件夹名 = skill_code) */
export async function uploadSkillZip(
file: File,
skillName: string,
priority: number,
): Promise<SkillDetailResult> {
const form = new FormData();
form.append('file', file);
form.append('skill_name', skillName);
form.append('priority', String(priority));
const res = await http.post<ApiResponse<SkillDetailResult>>('/skills/upload', form);
return res.data.data;
}
/* ---------- Scan Skills ---------- */
export interface ScanSkillResult {
skill_code: string;
skill_name: string;
status: 'imported' | 'skipped';
}
export interface ScanSkillsResponse {
total: number;
scanned: number;
imported: number;
skipped: number;
results: ScanSkillResult[];
}
/** 扫描 skills/ 目录,同步未入库的 skill */
export async function scanSkills(): Promise<ScanSkillsResponse> {
const res = await http.post<ApiResponse<ScanSkillsResponse>>('/skills/scan');
return res.data.data;
}
/* ---------- Customer Groups ---------- */
export interface CustomerGroupItem {
id: number;
customer_contact_id: string;
customer_name: string | null;
bot_id: string;
bot_code: string;
bot_name: string | null;
group_id: string | null;
group_name: string | null;
group_status: string;
member_bot_ids: string[];
member_bot_names: string[];
is_deleted: boolean;
created_at: string;
updated_at: string;
}
export interface CustomerGroupListData {
total: number;
page: number;
page_size: number;
list: CustomerGroupItem[];
status_counts: Record<string, number>;
}
export async function listCustomerGroups(params: {
page?: number;
page_size?: number;
keyword?: string;
status?: string;
}): Promise<CustomerGroupListData> {
const res = await http.get<ApiResponse<CustomerGroupListData>>('/customer-groups', { params });
return res.data.data;
}
/** 软删除客户群记录 */
export async function deleteCustomerGroup(id: number): Promise<void> {
await http.delete(`/customer-groups/${id}`);
}
/* ---------- Group Messages ---------- */
export interface GroupMessageItem {
id: number;
msg_id: string;
msg_time: string;
msg_type: string | null;
msg_content: string | null;
sender_id: string | null;
sender_name: string | null;
session_title: string | null;
bot_send: boolean;
bot_id: string;
bot_code: string;
created_at: string;
}
export async function listGroupMessages(
groupId: number,
params: { page?: number; page_size?: number } = {},
): Promise<GroupMessageItem[]> {
const res = await http.get<ApiResponse<GroupMessageItem[]>>(`/customer-groups/${groupId}/messages`, { params });
return res.data.data;
}
/* ---------- Customer Group Stats ---------- */
export interface DailyCount {
date: string;
count: number;
}
export interface ActiveGroupRank {
group_id: number;
group_name: string | null;
bot_id: string;
message_count: number;
}
export interface CustomerGroupStats {
total_groups: number;
total_messages: number;
total_active_groups: number;
daily_message_counts: DailyCount[];
daily_new_groups: DailyCount[];
top_active_groups: ActiveGroupRank[];
}
export async function getCustomerGroupStats(days: number = 30): Promise<CustomerGroupStats> {
const res = await http.get<ApiResponse<CustomerGroupStats>>('/customer-groups/stats', { params: { days } });
return res.data.data;
}
import axios from 'axios';
export interface ApiResponse<T> {
code: number;
message: string;
data: T;
trace_id?: string;
}
const http = axios.create({
baseURL: '/api/v1',
timeout: 30000,
});
http.interceptors.response.use(
(response) => {
const body = response.data as ApiResponse<unknown>;
// 后端 success_response_payload 返回 code=200(HTTP 状态码)
if (body.code >= 400) {
return Promise.reject(new Error(body.message || '请求失败'));
}
return response;
},
(error) => {
if (error.code === 'ERR_NETWORK') {
return Promise.reject(new Error('网络错误,请检查后端服务是否启动'));
}
return Promise.reject(error);
},
);
export default http;
import { NavLink } from 'react-router-dom';
import { useTheme } from '../hooks/useTheme';
interface NavItem {
path: string;
label: string;
icon: string;
}
const navItems: NavItem[] = [
{ path: '/agents/create', label: '新增 Agent', icon: '+' },
{ path: '/skills/create', label: '新增 Skill', icon: '◇' },
{ path: '/bots/qrcode/create', label: '新增机器人二维码', icon: '◉' },
{ path: '/customer-groups', label: '客户群', icon: '◉' },
];
export function Layout({ children }: { children: React.ReactNode }) {
const { theme, toggle } = useTheme();
return (
<div className="app-shell">
<aside className="sidebar">
<div className="sidebar-header">
<div className="sidebar-logo">
<span className="logo-icon">◆</span>
<span className="logo-text">Ops Console</span>
</div>
<div className="logo-subtitle">运维控制台</div>
</div>
<nav className="sidebar-nav">
{navItems.map((item) => (
<NavLink
key={item.path}
to={item.path}
end={item.path === '/'}
className={({ isActive }) =>
`nav-item${isActive ? ' active' : ''}`
}
>
<span className="nav-icon">{item.icon}</span>
<span className="nav-label">{item.label}</span>
</NavLink>
))}
</nav>
<div className="sidebar-footer">
<button className="theme-toggle" onClick={toggle} title={`切换到${theme === 'dark' ? '浅色' : '深色'}主题`}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
{theme === 'dark' ? (
<>
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" />
<line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" />
<line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</>
) : (
<>
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</>
)}
</svg>
<span className="theme-label">{theme === 'dark' ? '浅色模式' : '深色模式'}</span>
</button>
<span className="version-tag">v0.1.0</span>
</div>
</aside>
<main className="main-content">
{children}
</main>
</div>
);
}
import { useCallback, useEffect, useRef, useState } from 'react';
/* ---------- Single Select (searchable) ---------- */
interface SelectOption {
value: string;
label: string;
subtitle?: string;
disabled?: boolean;
}
interface SelectProps {
options: SelectOption[];
value: string;
onChange: (value: string) => void;
placeholder?: string;
searchable?: boolean;
loading?: boolean;
error?: string | null;
onRetry?: () => void;
mono?: boolean;
}
export function Select({
options,
value,
onChange,
placeholder = '请选择',
searchable = false,
loading = false,
error = null,
onRetry,
mono = false,
}: SelectProps) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
const ref = useRef<HTMLDivElement>(null);
const selected = options.find((o) => o.value === value);
const filtered = searchable
? options.filter(
(o) =>
o.label.toLowerCase().includes(search.toLowerCase()) ||
o.subtitle?.toLowerCase().includes(search.toLowerCase()),
)
: options;
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
setSearch('');
}
}
document.addEventListener('mousedown', handleClick);
return () => document.removeEventListener('mousedown', handleClick);
}, []);
const handleSelect = useCallback(
(opt: SelectOption) => {
if (opt.disabled) return;
onChange(opt.value);
setOpen(false);
setSearch('');
},
[onChange],
);
return (
<div className={`custom-select${mono ? ' mono' : ''}`} ref={ref}>
<div
className={`select-trigger${open ? ' open' : ''}${value ? ' has-value' : ''}`}
onClick={() => !loading && !error && setOpen(!open)}
>
<span className={`select-value${!selected ? ' placeholder' : ''}`}>
{loading ? '加载中...' : error ? '加载失败' : selected ? selected.label : placeholder}
</span>
<span className="select-arrow">▾</span>
</div>
{open && (
<div className="select-dropdown">
{loading && <div className="select-status">加载中...</div>}
{error && (
<div className="select-actions">
<span className="select-error-msg">{error}</span>
{onRetry && (
<button className="select-retry-btn" onClick={onRetry}>
重试
</button>
)}
</div>
)}
{!loading && !error && searchable && (
<div className="select-search-box">
<input
className="select-search-input"
placeholder="搜索..."
value={search}
onChange={(e) => setSearch(e.target.value)}
autoFocus
/>
</div>
)}
{!loading && !error && filtered.length === 0 && (
<div className="select-status">无匹配选项</div>
)}
{!loading &&
!error &&
filtered.map((opt) => (
<div
key={opt.value}
className={`select-option${opt.value === value ? ' selected' : ''}${opt.disabled ? ' disabled' : ''}`}
onClick={() => handleSelect(opt)}
>
<div className="select-option-label">{opt.label}</div>
{opt.subtitle && <div className="select-option-sub">{opt.subtitle}</div>}
</div>
))}
</div>
)}
</div>
);
}
/* ---------- Multi Select (checkbox dropdown) ---------- */
interface MultiSelectOption {
value: string;
label: string;
subtitle?: string;
}
interface MultiSelectProps {
options: MultiSelectOption[];
value: string[];
onChange: (value: string[]) => void;
placeholder?: string;
loading?: boolean;
error?: string | null;
onRetry?: () => void;
}
export function MultiSelect({
options,
value,
onChange,
placeholder = '请选择',
loading = false,
error = null,
onRetry,
}: MultiSelectProps) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const selectedLabels = options
.filter((o) => value.includes(o.value))
.map((o) => o.label);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
}
}
document.addEventListener('mousedown', handleClick);
return () => document.removeEventListener('mousedown', handleClick);
}, []);
function toggle(optValue: string) {
if (value.includes(optValue)) {
onChange(value.filter((v) => v !== optValue));
} else {
onChange([...value, optValue]);
}
}
return (
<div className="custom-select multi" ref={ref}>
<div
className={`select-trigger${open ? ' open' : ''}${value.length > 0 ? ' has-value' : ''}`}
onClick={() => !loading && !error && setOpen(!open)}
>
<span className={`select-value${value.length === 0 ? ' placeholder' : ''}`}>
{loading
? '加载中...'
: error
? '加载失败'
: value.length === 0
? placeholder
: `已选 ${value.length} 项`}
</span>
<span className="select-arrow">▾</span>
</div>
{open && (
<div className="select-dropdown">
{loading && <div className="select-status">加载中...</div>}
{error && (
<div className="select-actions">
<span className="select-error-msg">{error}</span>
{onRetry && (
<button className="select-retry-btn" onClick={onRetry}>
重试
</button>
)}
</div>
)}
{!loading && !error && options.length === 0 && (
<div className="select-status">暂无数据</div>
)}
{!loading &&
!error &&
options.map((opt) => (
<label key={opt.value} className="select-option multi-option">
<input
type="checkbox"
checked={value.includes(opt.value)}
onChange={() => toggle(opt.value)}
/>
<div className="multi-option-content">
<div className="select-option-label">{opt.label}</div>
{opt.subtitle && <div className="select-option-sub">{opt.subtitle}</div>}
</div>
</label>
))}
</div>
)}
{value.length > 0 && !open && (
<div className="select-tags">
{selectedLabels.map((label) => (
<span key={label} className="select-tag">
{label}
</span>
))}
</div>
)}
</div>
);
}
import { useCallback, useSyncExternalStore } from 'react';
function getSnapshot(): string {
return document.documentElement.getAttribute('data-theme') || 'dark';
}
function subscribe(callback: () => void): () => void {
const observer = new MutationObserver((mutations) => {
for (const m of mutations) {
if (m.type === 'attributes' && m.attributeName === 'data-theme') {
callback();
break;
}
}
});
observer.observe(document.documentElement, { attributes: true });
return () => observer.disconnect();
}
export function useTheme() {
const theme = useSyncExternalStore(subscribe, getSnapshot);
const toggle = useCallback(() => {
const next = theme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
}, [theme]);
return { theme, toggle, isDark: theme === 'dark' };
}
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './index.css';
const rootElement = document.getElementById('root');
if (!rootElement) {
throw new Error('Root element #root was not found.');
}
createRoot(rootElement).render(
<StrictMode>
<App />
</StrictMode>,
);
import { useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { uploadSkillZip, scanSkills, type ScanSkillsResponse } from '../api/agent';
export function CreateSkill() {
const navigate = useNavigate();
const fileRef = useRef<HTMLInputElement>(null);
const [skillName, setSkillName] = useState('');
const [priority, setPriority] = useState('1');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<{ skill_code: string; skill_name: string } | null>(null);
/* —— 扫描 —— */
const [scanning, setScanning] = useState(false);
const [scanResult, setScanResult] = useState<ScanSkillsResponse | null>(null);
async function handleScan() {
setScanning(true);
setScanResult(null);
setError(null);
try {
const data = await scanSkills();
setScanResult(data);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : '扫描失败');
} finally {
setScanning(false);
}
}
/* —— 上传创建 —— */
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0] ?? null;
setSelectedFile(file);
setResult(null);
setError(null);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setResult(null);
if (!skillName.trim()) {
setError('请输入 Skill 名称');
return;
}
const p = Number(priority);
if (!Number.isInteger(p) || p < 1) {
setError('优先级必须是大于等于 1 的整数');
return;
}
if (!selectedFile) {
setError('请选择要上传的 zip 文件');
return;
}
if (!selectedFile.name.endsWith('.zip')) {
setError('只支持 .zip 文件');
return;
}
setSubmitting(true);
try {
const res = await uploadSkillZip(selectedFile, skillName.trim(), p);
setResult({ skill_code: res.skill_code, skill_name: res.skill_name });
setSkillName('');
setPriority('1');
setSelectedFile(null);
if (fileRef.current) fileRef.current.value = '';
} catch (err: unknown) {
setError(err instanceof Error ? err.message : '创建失败');
} finally {
setSubmitting(false);
}
}
return (
<div className="page">
{/* —— 扫描区 —— */}
<div className="form-card" style={{ marginBottom: 24 }}>
<div className="form-card-header">
<span className="form-card-title">扫描同步</span>
</div>
<div className="form-body">
<p className="form-help-text">
扫描 <code>backend/skills/</code> 目录,将磁盘上已存在但数据库中未录入的 Skill 自动同步入库。
</p>
<button
className="btn btn-secondary"
onClick={handleScan}
disabled={scanning}
>
{scanning ? '扫描中...' : '扫描并同步'}
</button>
{scanResult && (
<div style={{ marginTop: 16 }}>
<div className="stat-row" style={{ marginBottom: 12, gap: 8 }}>
<div className="stat-card" style={{ flex: 1, padding: '8px 12px' }}>
<div className="stat-value" style={{ fontSize: 18 }}>{scanResult.total}</div>
<div className="stat-label">找到</div>
</div>
<div className="stat-card" style={{ flex: 1, padding: '8px 12px' }}>
<div className="stat-value" style={{ fontSize: 18, color: '#4ade80' }}>{scanResult.imported}</div>
<div className="stat-label">已导入</div>
</div>
<div className="stat-card" style={{ flex: 1, padding: '8px 12px' }}>
<div className="stat-value" style={{ fontSize: 18, color: '#94a3b8' }}>{scanResult.skipped}</div>
<div className="stat-label">已存在</div>
</div>
</div>
{scanResult.results.length > 0 && (
<table className="data-table" style={{ width: '100%' }}>
<thead>
<tr>
<th>skill_code</th>
<th>skill_name</th>
<th>状态</th>
</tr>
</thead>
<tbody>
{scanResult.results.map((r) => (
<tr key={r.skill_code}>
<td><code>{r.skill_code}</code></td>
<td>{r.skill_name}</td>
<td>
<span className={`tag ${r.status === 'imported' ? 'tag-success' : 'tag-muted'}`}>
{r.status === 'imported' ? '已导入' : '已存在'}
</span>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
)}
</div>
</div>
{/* —— 错误/成功 —— */}
{error && (
<div className="alert alert-error">
<span className="alert-icon">!</span>
<span>{error}</span>
</div>
)}
{result && (
<div className="alert alert-success">
<span className="alert-icon">✓</span>
<span>
Skill <code className="tag">{result.skill_name}</code> 创建成功
<span className="badge">{result.skill_code}</span>
</span>
</div>
)}
{/* —— 上传表单 —— */}
<div className="form-card">
<div className="form-card-header">
<span className="form-card-title">上传 Skill</span>
</div>
<form onSubmit={handleSubmit}>
<div className="form-body">
<div className="form-row">
<div className="form-group">
<label className="form-label">
Skill 名称 <span className="required">*</span>
</label>
<input
className="form-input"
placeholder="例:会议纪要助手"
value={skillName}
onChange={(e) => setSkillName(e.target.value)}
/>
</div>
<div className="form-group">
<label className="form-label">
优先级 <span className="required">*</span>
</label>
<input
type="number"
min={1}
className="form-input mono"
value={priority}
onChange={(e) => setPriority(e.target.value)}
/>
</div>
</div>
<div className="form-group">
<label className="form-label">
上传 zip 包 <span className="required">*</span>
</label>
<div className="upload-zone">
<input
ref={fileRef}
type="file"
accept=".zip"
onChange={handleFileChange}
className="upload-input"
/>
{selectedFile ? (
<div className="upload-info">
<span className="upload-icon">📦</span>
<span>{selectedFile.name}</span>
<span className="upload-size">({(selectedFile.size / 1024).toFixed(1)} KB)</span>
</div>
) : (
<div className="upload-placeholder">
选择 .zip 文件,文件夹名将作为 skill_code
</div>
)}
</div>
<span className="form-hint">
zip 内需包含一个顶层文件夹(如 <code>meeting_minutes/</code>),内含 <code>SKILL.md</code>;
frontmatter 中的 <code>description</code> 字段将作为 Skill 描述
</span>
</div>
</div>
<div className="form-footer">
<button type="submit" className="btn btn-primary" disabled={submitting}>
{submitting ? '上传中...' : '创建 Skill'}
</button>
<button type="button" className="btn btn-ghost" onClick={() => navigate('/')}>
取消
</button>
</div>
</form>
</div>
</div>
);
}
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { listGroupMessages, type GroupMessageItem } from '../api/agent';
const PAGE_SIZE = 100;
export function CustomerGroupChat() {
const { groupId } = useParams<{ groupId: string }>();
const navigate = useNavigate();
const scrollRef = useRef<HTMLDivElement>(null);
const [messages, setMessages] = useState<GroupMessageItem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const load = useCallback(async (p: number) => {
if (!groupId) return;
setLoading(true);
setError(null);
try {
const data = await listGroupMessages(Number(groupId), { page: p, page_size: PAGE_SIZE });
if (p === 1) {
setMessages(data);
} else {
setMessages((prev) => [...data, ...prev]);
}
setHasMore(data.length >= PAGE_SIZE);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : '加载失败');
} finally {
setLoading(false);
}
}, [groupId]);
useEffect(() => {
load(1);
}, [load]);
// Auto-scroll to bottom when messages first load or new messages appear
useEffect(() => {
if (scrollRef.current && page === 1) {
requestAnimationFrame(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
});
}
}, [messages, page]);
function handleLoadMore() {
const next = page + 1;
setPage(next);
load(next);
}
function formatTime(ts: string): string {
if (!ts) return '';
const d = new Date(ts);
const pad = (n: number) => String(n).padStart(2, '0');
return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
return (
<div className="page chat-page">
{/* Header */}
<div className="chat-header">
<button className="chat-back" onClick={() => navigate('/customer-groups')}>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="15 18 9 12 15 6" />
</svg>
</button>
<div className="chat-header-info">
<div className="chat-header-title">群聊天记录</div>
<div className="chat-header-sub">群 ID: {groupId}</div>
</div>
</div>
{/* Load More */}
{hasMore && !loading && (
<div className="chat-load-more">
<button className="chat-load-btn" onClick={handleLoadMore}>加载更多</button>
</div>
)}
{loading && <div className="chat-load-more"><span className="chat-loading-text">加载中...</span></div>}
{/* Error */}
{error && (
<div className="alert alert-error" style={{ margin: '8px 16px' }}>
<span className="alert-icon">!</span>
<span>{error}</span>
</div>
)}
{/* Messages */}
<div className="chat-messages" ref={scrollRef}>
{!loading && messages.length === 0 && (
<div className="chat-empty">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
<line x1="9" y1="10" x2="15" y2="10" />
</svg>
<span>暂无聊天记录</span>
</div>
)}
{messages.map((msg) => {
const isBot = msg.bot_send;
return (
<div key={msg.id} className={`chat-msg ${isBot ? 'chat-msg-user' : 'chat-msg-bot'}`}>
<div className="chat-msg-sender">{isBot ? (msg.sender_name || '机器人') : (msg.sender_name || '客户')}</div>
<div className="chat-msg-bubble">
<div className="chat-msg-text">{msg.msg_content || `[${msg.msg_type || '未知类型'}]`}</div>
<div className="chat-msg-time">{formatTime(msg.msg_time)}</div>
</div>
</div>
);
})}
</div>
</div>
);
}
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
host: '0.0.0.0',
port: 5180,
proxy: {
'/api': {
target: 'http://127.0.0.1:8082',
changeOrigin: true,
},
},
},
preview: {
host: '0.0.0.0',
},
})
--- ---
name: meeting_minutes name: meeting_minutes
description: 会议录音转写、纯文本会议记录整理、纪要生成与文件导出。上传音视频文件 → Fun-ASR 转写 → Qwen3.6-plus 生成结构化 Markdown 会议纪要,或直接输入纯文本会议记录 → 生成结构化 Markdown 会议纪要 → 导出 docx → 上传 OSS 返回查看链接
--- ---
# 会议纪要助手 # 会议纪要助手
你是会议纪要助手,职责是将用户提供的会议录音或纯文本会议记录转化为结构化会议纪要并导出为 docx 文件。 你是会议纪要助手,职责是将用户提供的会议录音或纯文本会议记录转化为结构化会议纪要并导出为 docx 文件。
收到用户请求后,严格按以下步骤执行。 收到用户请求后,严格按以下步骤执行。
## 输入识别 ## 输入识别
从用户消息中提取以下信息: 从用户消息中提取以下信息:
...@@ -62,7 +63,6 @@ python skills/meeting_minutes/scripts/generate_minutes.py https://example.com/au ...@@ -62,7 +63,6 @@ python skills/meeting_minutes/scripts/generate_minutes.py https://example.com/au
- 转写为异步任务,需等待 Fun-ASR 完成,可能需要几分钟 - 转写为异步任务,需等待 Fun-ASR 完成,可能需要几分钟
- 脚本通过 stdout 输出 Markdown 纪要,stderr 输出进度信息 - 脚本通过 stdout 输出 Markdown 纪要,stderr 输出进度信息
#### 场景 B:用户直接提供纯文本会议记录 #### 场景 B:用户直接提供纯文本会议记录
将用户提供的会议记录文本写入临时文件后执行: 将用户提供的会议记录文本写入临时文件后执行:
...@@ -88,10 +88,8 @@ cat tmp_minutes.txt | python skills/meeting_minutes/scripts/generate_minutes.py ...@@ -88,10 +88,8 @@ cat tmp_minutes.txt | python skills/meeting_minutes/scripts/generate_minutes.py
- 会议记录文本应尽量保持原始顺序,避免提前人工删改关键信息 - 会议记录文本应尽量保持原始顺序,避免提前人工删改关键信息
- 脚本通过 stdout 输出 Markdown 纪要,stderr 输出进度信息 - 脚本通过 stdout 输出 Markdown 纪要,stderr 输出进度信息
### Step 2: 导出 docx + 上传 OSS ### Step 2: 导出 docx + 上传 OSS
把 Step 1 获取到的 Markdown 内容通过管道传给导出脚本: 把 Step 1 获取到的 Markdown 内容通过管道传给导出脚本:
```bash ```bash
...@@ -110,6 +108,7 @@ echo "<Step1的Markdown内容>" | python skills/meeting_minutes/scripts/export_m ...@@ -110,6 +108,7 @@ echo "<Step1的Markdown内容>" | python skills/meeting_minutes/scripts/export_m
2. docx 查看链接:必须单独占一行输出 URL,且链接前后不要加任何标点、反引号或代码块 2. docx 查看链接:必须单独占一行输出 URL,且链接前后不要加任何标点、反引号或代码块
**交付格式校验**: **交付格式校验**:
- 必须使用纯自然语言交付,禁止使用任何格式化标记(如 Markdown 加粗、斜体、列表等)。 - 必须使用纯自然语言交付,禁止使用任何格式化标记(如 Markdown 加粗、斜体、列表等)。
- 严禁使用双星号 `**` 进行加粗。 - 严禁使用双星号 `**` 进行加粗。
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!