diff --git a/.env.example b/.env.example index 0d29a58..b62fef6 100644 --- a/.env.example +++ b/.env.example @@ -7,7 +7,7 @@ # 缺少 backend/.env 时从后端模板创建,只补齐缺失或空的认证密钥,不覆盖已有合法值。 # 普通部署项由 backend/app/config.py 定义,进程环境变量优先于 backend/.env。 -# 个人模型凭据:登录后在“设置 → 模型与服务”保存 DeepSeek Key、MinerU Token。 +# 个人模型凭据:登录后在“个人中心 → API 配置”保存 DeepSeek Key、MinerU Token。 # MinerU 优先使用当前操作者的个人 Token;未配置时使用 # backend/app/local_secrets.py 中的 MINERU_DEFAULT_TOKEN。 # 系统默认凭据的占位格式见 backend/app/local_secrets.example.py,真实文件不得提交。 diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index dc8a8be..2ef545f 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -80,8 +80,8 @@ jobs: cache-dependency-path: frontend/package-lock.json - name: Install locked frontend dependencies run: npm ci - - name: Install Chromium and system dependencies - run: npx --no-install playwright-core install --with-deps chromium + - name: Install Chromium + run: npx --no-install playwright-core install chromium - name: ESLint run: npm run lint - name: TypeScript, build and offline regressions diff --git a/README.md b/README.md index 5c1f678..5e2dd43 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ MathCraft 面向教师与学生,提供题库协作、文档解析与检索、 对话提供快速出题、创新命题、知识答疑和数据管理四模式,右侧历史会话支持继续已有对话。出题先命制题干,再独立解题生成答案、选项和解析,审核后按题型缺口尝试补齐;界面通过进度轮询等待结果。题目预览中勾选题目后可导出 Word,设置题型顺序、答案和解析的位置。 -试卷支持关闭和恢复作答,删除保留已有作答及成绩;出题任务状态存入 SQL,服务重启后未完成的任务标为中断,用户可重新发起。预览页一键清空只删除题目,保留对话;运行期间暂不可清空,后台取消和最终提交继续校验运行身份。 +试卷支持关闭和恢复作答,删除保留已有作答及成绩;出题任务状态存入 SQL,服务重启后未完成的任务标为中断,用户可重新发起。一键清空删除当前预览的题目并保留对话。生成期间和暂停待确认期间,清空按钮禁用。若暂停前本轮已保存,先恢复结果供用户查看和清空。 学习空间可在停止作答后移除尚无作答记录的发布;已有作答保留历史入口。删除未完成的题库与资料在管理页提供继续清理入口。 @@ -111,14 +111,14 @@ OpenAI 兼容客户端使用 `openai<3`:当前追踪适配基于 `httpx`,不 | `DATABASE_URL` | 默认 `sqlite:///./data/mathcraft.db` | | `REDIS_URL` | 默认 `redis://127.0.0.1:6379/0`,与上一步的服务一致 | | `AUTH_JWT_SECRET`、`AUTH_CODE_SECRET` | 由初始化脚本生成,保留生成值 | -| `DEEPSEEK_API_KEY` | 可填部署默认 Key,也可登录后在“设置 → 模型与服务”保存个人 Key | +| `DEEPSEEK_API_KEY` | 可填部署默认 Key,也可登录后在“个人中心 → API 配置”保存个人 Key | | `SMTP_*` | 使用邮箱验证码登录、找回密码或绑定邮箱时配置 | 上述复制命令仅在缺少 `app/local_secrets.py` 时创建占位配置,已有文件保留。首次账号密码登录无需真实模型凭据,使用模型功能前再配置对应服务。 已有 `.env` 不会被模板覆盖,需手动核对开发开关。后端环境配置以 [backend/app/config.py](backend/app/config.py) 为准,进程环境变量优先于固定位置的 `backend/.env`;修改后需重启后端。唯一可复制的后端环境模板为 [backend/.env.example](backend/.env.example),根 [.env.example](.env.example) 仅作配置入口指引,当前前后端均不读取根 `.env`。 -MinerU Token 在“设置 → 模型与服务”保存,个人配置优先;部署默认 Token 使用 `app/local_secrets.py` 的 `MINERU_DEFAULT_TOKEN`。旧 `MINERU_MODE`、`MINERU_API_BASE_URL`、`MINERU_API_TOKEN` 不生效,已有本机文件不会自动迁移。嵌入和重排模型仍由管理员“模型与检索”维护。 +MinerU Token 在“个人中心 → API 配置”保存,个人配置优先;部署默认 Token 使用 `app/local_secrets.py` 的 `MINERU_DEFAULT_TOKEN`。旧 `MINERU_MODE`、`MINERU_API_BASE_URL`、`MINERU_API_TOKEN` 不生效,已有本机文件不会自动迁移。嵌入和重排模型仍由管理员“模型与检索”维护。 平台生成模型凭据支持管理员接口 `/api/admin/llm-settings`,使用 `cryptography` 加密保存。调用优先使用个人 Key,其次为平台凭据,最后为部署默认;个人 Key 被模型服务拒绝时可回退平台配置。加密主密钥位于上传目录父级的 `secret.key`(默认 `backend/data/secret.key`),备份数据库时一并备份该文件。 @@ -170,7 +170,7 @@ node node_modules/vite/bin/vite.js --host 127.0.0.1 --port 5173 --strictPort 前端隔离项目环境文件,根 `.env` 和 `frontend/.env` 均不会被 Vite 加载;自定义公开 API 地址需在开发启动或构建前通过进程环境变量 `VITE_API_BASE_URL` 注入。监听地址与端口使用上述命令行参数,开发代理目标由 `frontend/vite.config.ts` 定义;`VITE_*` 会进入浏览器代码,不得放入凭据。详见[前端配置说明](frontend/README.md#构建与检查)。 -教师、学生账号由管理员开通。个人 DeepSeek Key 和 MinerU Token 在“设置 → 模型与服务”配置;平台嵌入、重排模型由管理员在“模型与检索”配置。嵌入模型或服务地址变更后,需重建索引才能应用。 +教师、学生账号由管理员开通。个人 DeepSeek Key 和 MinerU Token 在“个人中心 → API 配置”配置,未配置 DeepSeek Key 时智能出题不可发送;平台嵌入、重排模型由管理员在“模型与检索”配置。嵌入模型或服务地址变更后,需重建索引才能应用。 部署默认的硅基流动与 MinerU 凭据配置方式见 [模型配置说明](docs/design/模型配置来源与普通知识库流程.md),占位格式见 [local_secrets.example.py](backend/app/local_secrets.example.py)。 diff --git a/backend/.env.example b/backend/.env.example index 9ab02b4..f51db2a 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,13 +1,13 @@ # 当前 FastAPI 后端的环境配置模板,实际读取 backend/.env;进程环境变量优先。 # 仓库根 .env.example 仅作入口指引,不要把根模板复制成后端配置。 -# MinerU Token 不在本文件配置:登录后在“设置 → 模型与服务”保存个人 Token; +# MinerU Token 不在本文件配置:登录后在“个人中心 → API 配置”保存个人 Token; # 未配置个人 Token 时,使用 app/local_secrets.py 的 MINERU_DEFAULT_TOKEN。 # 嵌入与重排服务优先由管理员在“模型与检索”维护,详见 README.md。 DATABASE_URL=sqlite:///./data/mathcraft.db REDIS_URL=redis://127.0.0.1:6379/0 -# DeepSeek 密钥优先取每个用户在“设置 → 模型与服务”的配置,此处仅兜底 +# DeepSeek 密钥优先取每个用户在“个人中心 → API 配置”的配置,此处仅兜底 DEEPSEEK_API_KEY= DEEPSEEK_BASE_URL=https://api.deepseek.com DEEPSEEK_MODEL=deepseek-flash diff --git a/backend/README.md b/backend/README.md index 90c61a4..c9371a2 100644 --- a/backend/README.md +++ b/backend/README.md @@ -92,7 +92,7 @@ OpenAI SDK 使用 `openai<3`:当前追踪客户端基于 `httpx`,不兼容 S 配置以 [app/config.py](app/config.py) 为准,环境变量优先于固定位置的 `backend/.env`。SQLite 相对路径按启动工作目录解析,其他存储目录相对路径以 `backend/` 为基准。修改配置后重启服务。 -DeepSeek 与 MinerU 个人凭据在应用“设置 → 模型与服务”保存;嵌入、重排模型与凭据由管理员在“模型与检索”维护。部署默认值及优先级见 [模型配置说明](../docs/design/模型配置来源与普通知识库流程.md)。 +DeepSeek 与 MinerU 个人凭据在应用“个人中心 → API 配置”保存;嵌入、重排模型与凭据由管理员在“模型与检索”维护。部署默认值及优先级见 [模型配置说明](../docs/design/模型配置来源与普通知识库流程.md)。 后端环境模板只有本目录的 [.env.example](.env.example),仓库根模板仅作配置入口指引。MinerU Token 不从 `.env` 读取:个人 Token 优先,没有时使用 `app/local_secrets.py` 中的 `MINERU_DEFAULT_TOKEN`,格式见 [占位样例](app/local_secrets.example.py)。旧 `MINERU_MODE`、`MINERU_API_BASE_URL`、`MINERU_API_TOKEN` 不属于当前后端配置;已有 `.env` 中这些字段不会自动迁移或覆盖个人设置。OCR 地址和解析模型仍由 `app/services/mineru.py` 固定。 diff --git a/backend/alembic/versions/q2d3e4f56789_chat_requests.py b/backend/alembic/versions/q2d3e4f56789_chat_requests.py new file mode 100644 index 0000000..e77863b --- /dev/null +++ b/backend/alembic/versions/q2d3e4f56789_chat_requests.py @@ -0,0 +1,31 @@ +"""持久化对话轮次状态、取消占位和已发布回复。""" + +import sqlalchemy as sa +from alembic import op + +revision = "q2d3e4f56789" +down_revision = "p1c2d3e45678" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """添加轮次表,保留已有的会话与消息。""" + op.create_table( + "chat_requests", + sa.Column("session_id", sa.String(40), nullable=False), + sa.Column("request_id", sa.String(36), nullable=False), + sa.Column("run_id", sa.String(40)), + sa.Column("status", sa.String(16), nullable=False), + sa.Column("execution_finished_at", sa.DateTime(timezone=True)), + sa.Column("batch_id", sa.String(40)), + sa.Column("result_json", sa.Text()), + sa.PrimaryKeyConstraint("session_id", "request_id"), + sa.ForeignKeyConstraint(["session_id"], ["chat_sessions.id"], ondelete="CASCADE"), + sa.UniqueConstraint("run_id"), + ) + + +def downgrade() -> None: + """移除新增的轮次记录表。""" + op.drop_table("chat_requests") diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index ccb9444..8afcc62 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -1,20 +1,23 @@ """对话出题:SQL 保存完整会话与运行状态,取消和最终提交按 run_id 隔离。""" import json from dataclasses import dataclass +from uuid import UUID from fastapi import APIRouter, Depends from redis.exceptions import RedisError -from sqlalchemy import case, or_, update +from sqlalchemy import case, or_, select, update from sqlalchemy.orm import Query, Session from app.db import SessionLocal, get_db from app.deps import get_current_user, resolve_bank_access from app.errors import AppError -from app.models import ChatMessage, ChatSession, Document, OpsRun, User +from app.models import Bank, ChatMessage, ChatRequest, ChatSession, Document, Favorite, OpsRun, User from app.models.base import new_id, utcnow from app.models.ops_run import RunEntrypoint, RunErrorCode, RunStatus +from app.models.question import Question as SavedQuestion from app.schemas.api import ( - ChatConfirmBody, ChatMessageBody, ChatSessionCreateBody, ChatSessionDetailResponse, + ChatConfirmBody, ChatMessageBody, ChatMessageResponse, ChatRequestResponse, + ChatSavedQuestion, ChatSessionCreateBody, ChatSessionDetailResponse, ) from app.schemas.auth import ErrorResponse from app.schemas.question import GenerateParams, Question @@ -133,7 +136,8 @@ def _write_progress(session_id: str, run_id: str, percent: int, stage: str) -> N def _begin_run( db: Session, session_id: str, user_id: str, *, auth_version: int | None = None, -) -> ChatSession: + request_id: str | None = None, +) -> ChatSession | ChatRequest: """短事务串行化开始/取消/最终提交;提交后才允许执行模型。""" if auth_version is None: user = db.get(User, user_id) @@ -146,19 +150,34 @@ def _begin_run( s = db.get(ChatSession, session_id, populate_existing=True) if s is None or s.user_id != user_id: raise AppError("CHAT_SESSION_NOT_FOUND", "对话不存在", 404) - if s.run_status == "running": + if request_id is not None: + previous = db.get(ChatRequest, (session_id, request_id), populate_existing=True) + if previous is not None: + db.commit() + return previous + unfinished = db.scalar(select(ChatRequest.request_id).where( + ChatRequest.session_id == session_id, ChatRequest.execution_finished_at.is_(None), + ).limit(1)) + if s.run_status == "running" or unfinished is not None: db.rollback() raise AppError("CHAT_BUSY", "本对话已有进行中的请求,请等待完成或暂停后重试", 409) - generation.validate_resources(db, user_id, s.bank_id, s.document_id) + if request_id is None: + generation.validate_resources(db, user_id, s.bank_id, s.document_id) trace_id = current_run_id() # 被嵌套请求继承的追踪上下文可能属于旧运行,不能复用其取消标识或台账主键。 - if trace_id and (trace_id in {s.run_id, s.canceled_run_id} or db.get(OpsRun, trace_id)): + if trace_id and (trace_id in {s.run_id, s.canceled_run_id} or db.get(OpsRun, trace_id) + or db.scalar(select(ChatRequest.request_id).where( + ChatRequest.run_id == trace_id, + ))): trace_id = None s.run_id = trace_id or new_id("run") s.run_status = "running" s.run_progress = 0 s.run_stage = "正在准备" - # canceled_run_id 保留旧运行的取消事实,绝不在开始新运行时清空。 + if request_id is not None: + db.add(ChatRequest( + session_id=session_id, request_id=request_id, run_id=s.run_id, status="running", + )) db.commit() return s @@ -229,11 +248,16 @@ def _begin_generation( def _end_failed_run(session_id: str, run_id: str) -> None: - """异常收尾只影响自己的 run;已取消或已被后继替换的运行保持原样。""" + """工作事务和执行权释放后,记录该运行的退出及未发布结果的终态。""" with SessionLocal() as db: - _current_run(db, session_id, run_id).update({ + changed = _current_run(db, session_id, run_id).update({ "run_status": "failed", "run_stage": "请求未完成,请重试", }, synchronize_session=False) + request = db.scalar(select(ChatRequest).where(ChatRequest.run_id == run_id)) + if request is not None: + if request.status == "running": + request.status = "failed" if changed else "canceled" + request.execution_finished_at = utcnow() db.commit() @@ -248,6 +272,65 @@ def _paused_result(db: Session, session_id: str) -> dict: } +def _saved_questions( + db: Session, s: ChatSession, batch_id: str, +) -> list[ChatSavedQuestion]: + rows = db.execute( + select(SavedQuestion, Document.name, Favorite) + .select_from(SavedQuestion) + .join(Bank, Bank.id == SavedQuestion.bank_id) + .join(Document, (Document.id == SavedQuestion.document_id) + & (Document.bank_id == Bank.id)) + .outerjoin(Favorite, (Favorite.question_id == SavedQuestion.id) + & (Favorite.user_id == s.user_id)) + .where( + SavedQuestion.batch_id == batch_id, SavedQuestion.created_by == s.user_id, + SavedQuestion.bank_id == s.bank_id, SavedQuestion.document_id == s.document_id, + Bank.status == "active", Document.status != "deleting", + ) + .order_by(SavedQuestion.created_at, SavedQuestion.id) + ) + return [ + ChatSavedQuestion.model_validate(generation.question_to_api( + question, starred=favorite is not None, + favorite_group_id=favorite.group_id if favorite is not None else None, + doc_name=doc_name, + )) + for question, doc_name, favorite in rows + ] + + +def _request_response( + db: Session, s: ChatSession, user: User, request: ChatRequest, +) -> ChatRequestResponse: + result = ( + ChatMessageResponse.model_validate_json(request.result_json) + if request.result_json is not None else None + ) + if result is not None: + resolve_bank_access(db, user, s.bank_id) + if request.batch_id is not None: + result.questions = list(_saved_questions(db, s, request.batch_id)) + return ChatRequestResponse( + status=request.status, execution_finished=request.execution_finished_at is not None, + batch_id=request.batch_id, result=result, + ) + + +def _replay_request( + db: Session, s: ChatSession, user: User, request: ChatRequest, +) -> ChatMessageResponse: + if request.status == "canceled": + return ChatMessageResponse.model_validate(_paused_result(db, s.id)) + if request.status == "done": + result = _request_response(db, s, user, request).result + assert result is not None + return result + if request.status == "running": + raise AppError("CHAT_BUSY", "本轮请求正在处理,请查询处理状态", 409) + raise AppError("CHAT_REQUEST_FINISHED", "本轮请求已结束,请使用新的请求标识重试", 409) + + @router.post("/sessions", status_code=201) def create_session( body: ChatSessionCreateBody, @@ -286,7 +369,7 @@ def get_session( } -@router.post("/sessions/{session_id}/messages", responses={ +@router.post("/sessions/{session_id}/messages", response_model=ChatMessageResponse, responses={ 409: {"model": ErrorResponse, "description": "当前会话正在处理消息,请稍后再试"}, }) @trace_run("conversation", force_new=True) @@ -295,55 +378,76 @@ def send_message( body: ChatMessageBody, user: User = Depends(get_current_user), db: Session = Depends(get_db), -): +) -> ChatMessageResponse: """运行状态先提交,题目、两条消息与完整会话状态最后一次提交。""" user_id, auth_version = user.id, user.auth_version s = _get_session(session_id, user, db) - with conversation_turn(session_id): - return _send_message(session_id, body, user, db, s, user_id, auth_version) + request_id = str(body.request_id) if body.request_id is not None else None + if request_id is not None: + previous = db.get(ChatRequest, (session_id, request_id)) + if previous is not None: + return _replay_request(db, s, user, previous) + run_id = None + try: + with conversation_turn(session_id): + api_key = _message_api_key(db, s, user_id) if request_id is None else None + interrupted_stage = s.run_stage if s.run_status == "interrupted" else "" + claim = _begin_run( + db, session_id, user_id, auth_version=auth_version, request_id=request_id, + ) + if isinstance(claim, ChatRequest): + return _replay_request(db, s, user, claim) + run_id = claim.run_id + assert run_id is not None + return _send_message( + session_id, body, user, db, claim, user_id, run_id, interrupted_stage, api_key, + ) + finally: + if run_id is not None: + db.rollback() + _end_failed_run(session_id, run_id) + + +def _message_api_key(db: Session, s: ChatSession, user_id: str) -> str: + generation.validate_resources(db, user_id, s.bank_id, s.document_id) + api_key = get_effective_deepseek_key(db, user_id) + if not api_key: + raise AppError( + "DEEPSEEK_KEY_MISSING", "尚未配置 DeepSeek API Key,请到个人中心 → API 配置中填写", 400, + ) + return api_key def _send_message( session_id: str, body: ChatMessageBody, user: User, db: Session, s: ChatSession, - user_id: str, auth_version: int, -) -> dict: + user_id: str, run_id: str, interrupted_stage: str, api_key: str | None, +) -> ChatMessageResponse: """持有会话执行权直至当前消息确认停止或完成。""" - generation.validate_resources(db, user.id, s.bank_id, s.document_id) - api_key = get_effective_deepseek_key(db, user.id) - if not api_key: - raise AppError("DEEPSEEK_KEY_MISSING", "尚未配置 DeepSeek API Key,请到设置 → 模型与服务中填写", 400) - # 升级前待续内容仅在 Redis 中;切换不能被静默当作已经接续。 - interrupted_stage = s.run_stage if s.run_status == "interrupted" else "" - s = _begin_run(db, session_id, user_id, auth_version=auth_version) - run_id = s.run_id - assert run_id is not None run = GenerationRun( RunEntrypoint.CONVERSATION, user_id, s.bank_id, s.document_id, session_id=session_id, ) - try: - with run.observe(db): + with run.observe(db): + try: + if _is_canceled(session_id, run_id): + raise ChatCanceled + if api_key is None: + api_key = _message_api_key(db, s, user_id) + return _run_message(db, user, s, body, api_key, run_id, run=run, + interrupted_stage=interrupted_stage) + except ChatCanceled: + db.rollback() try: - return _run_message(db, user, s, body, api_key, run_id, run=run, - interrupted_stage=interrupted_stage) - except ChatCanceled: - # 取消事实只在执行器停止并回滚业务事务后写入台账。 - db.rollback() - try: - run.cancel() - except RunConflictError: - # 删除会话可能刚将旧快照改为 unknown;重读后确认取消。 - run.cancel() - return _paused_result(db, session_id) - finally: - # 回滚工作 Session 的读快照/失败写事务,随后才用独立短事务收尾。 - db.rollback() - _end_failed_run(session_id, run_id) + run.cancel() + except RunConflictError: + # 删除会话可能刚将旧快照改为 unknown;重读后确认取消。 + run.cancel() + return ChatMessageResponse.model_validate(_paused_result(db, session_id)) def _run_message( db: Session, user: User, s: ChatSession, body: ChatMessageBody, api_key: str, run_id: str, *, run: GenerationRun, interrupted_stage: str = "", -) -> dict: +) -> ChatMessageResponse: session_id, user_id, bank_id, document_id = s.id, user.id, s.bank_id, s.document_id doc = db.get(Document, document_id) if doc is None: @@ -556,7 +660,7 @@ def _commit_turn( params: GenerateParams | None = None, hyde_text: str | None = None, questions: list[Question] | None = None, run: GenerationRun | None = None, failure_code: RunErrorCode | None = None, -) -> dict: +) -> ChatMessageResponse: """所有模型已完成后,锁内重新验证 run 和资源,单次提交整轮结果。""" db.rollback() auth.assert_version(db, user_id, state.auth_version) @@ -585,6 +689,21 @@ def _commit_turn( s.pending_images_json = json.dumps(state.pending_images, ensure_ascii=False) s.last_message_at = utcnow() s.run_status, s.run_progress, s.run_stage = "done", 100, "" + response = ChatMessageResponse.model_validate({ + "reply": result["reply"], "slot_state": result["slot_state"], + "questions": result["questions"], "done": result["done"], "batch_id": batch_id, + "kind": result.get("kind", "reply"), "mode": state.mode, + "mode_changed": result.get("mode_changed", False), + "suggested_template": result.get("suggested_template"), "confirm": result.get("confirm"), + }) + if body.request_id is not None: + request = db.get(ChatRequest, (session_id, str(body.request_id))) + assert request is not None and request.run_id == run_id and request.status == "running" + request.status = "done" + request.batch_id = batch_id + request.result_json = response.model_copy(update={"questions": []}).model_dump_json() + if batch_id is not None: + response.questions = list(_saved_questions(db, s, batch_id)) if batch_id is None and run is not None and run.run_id is not None: _transition_chat_ledger( db, session_id, user_id, run_id, RunStatus.FAILED, @@ -610,13 +729,7 @@ def _commit_turn( raise if run is not None and run.run_id is not None: run.committed() - return { - "reply": result["reply"], "slot_state": result["slot_state"], - "questions": result["questions"], "done": result["done"], "batch_id": batch_id, - "kind": result.get("kind", "reply"), "mode": state.mode, - "mode_changed": result.get("mode_changed", False), - "suggested_template": result.get("suggested_template"), "confirm": result.get("confirm"), - } + return response @router.post("/sessions/{session_id}/confirm") @@ -669,24 +782,68 @@ def read_generation_progress( "stage": s.run_stage if active or s.run_status == "interrupted" else ""} +@router.get("/sessions/{session_id}/requests/{request_id}") +def read_chat_request( + session_id: str, + request_id: UUID, + user: User = Depends(get_current_user), + db: Session = Depends(get_db), +) -> ChatRequestResponse: + """读取属于本会话的指定轮次及其已提交回复。""" + s = _get_session(session_id, user, db) + request = db.get(ChatRequest, (session_id, str(request_id))) + if request is None: + raise AppError("CHAT_REQUEST_NOT_FOUND", "对话请求不存在", 404) + return _request_response(db, s, user, request) + + +def _cancel_active_run( + db: Session, session_id: str, user_id: str, run_id: str | None, +) -> None: + changed = db.execute(update(ChatSession).where( + ChatSession.id == session_id, ChatSession.user_id == user_id, + ChatSession.run_status == "running", ChatSession.run_id == run_id, + ).values(canceled_run_id=run_id, run_status="canceled", + run_progress=0, run_stage="已收到暂停请求").returning(ChatSession.id)) + if changed.scalar_one_or_none() is not None and run_id is not None: + db.execute(update(ChatRequest).where( + ChatRequest.session_id == session_id, ChatRequest.run_id == run_id, + ChatRequest.status == "running", + ).values(status="canceled")) + + @router.post("/sessions/{session_id}/cancel", status_code=202) def cancel_generation( session_id: str, user: User = Depends(get_current_user), db: Session = Depends(get_db), -): + request_id: UUID | None = None, +) -> ChatRequestResponse | dict[str, bool]: """原子绑定当前运行的取消事实;与开始和最终提交使用同一 SQL 行锁。""" s = _get_session(session_id, user, db) target_run_id = s.run_id - user_id = user.id + user_id, auth_version = user.id, user.auth_version db.rollback() + if request_id is None: + _cancel_active_run(db, session_id, user_id, target_run_id) + db.commit() + return {"canceled": True} + auth.assert_version(db, user_id, auth_version) db.execute(update(ChatSession).where( ChatSession.id == session_id, ChatSession.user_id == user_id, - ChatSession.run_status == "running", ChatSession.run_id == target_run_id, - ).values(canceled_run_id=target_run_id, run_status="canceled", - run_progress=0, run_stage="已收到暂停请求")) + ).values(run_status=ChatSession.run_status)) + s = _get_session(session_id, user, db) + request = db.get(ChatRequest, (session_id, str(request_id)), populate_existing=True) + if request is None: + request = ChatRequest( + session_id=session_id, request_id=str(request_id), status="canceled", + execution_finished_at=utcnow(), + ) + db.add(request) + elif request.status == "running": + _cancel_active_run(db, session_id, user_id, request.run_id) db.commit() - return {"canceled": True} + return _request_response(db, s, user, request) @router.delete("/sessions/{session_id}", status_code=204) diff --git a/backend/app/api/users.py b/backend/app/api/users.py index 3dc78b7..cfda721 100644 --- a/backend/app/api/users.py +++ b/backend/app/api/users.py @@ -12,7 +12,7 @@ from app.models import User from app.schemas.auth import ( CurrentPasswordBody, EmailBindingBody, EmailChangeBody, EmailCommitBody, - ModelSettingsBody, UserNoBody, + ModelSettingsBody, ModelTestBody, UserNoBody, ) from app.api.auth_http import clear_refresh, refresh_belongs_to_user from app.models import EmailChange @@ -127,11 +127,16 @@ def save_model_settings( @router.post("/model-settings/test-deepseek") -def test_deepseek(user: User = Depends(get_current_user), db: Session = Depends(get_db)): - """测试 DeepSeek 连接,失败仅返回固定脱敏提示。""" +def test_deepseek( + body: ModelTestBody | None = None, + user: User = Depends(get_current_user), + db: Session = Depends(get_db), +): + """测试 DeepSeek 连接;body 提供输入值时优先测试该值,不落库。失败仅返回固定脱敏提示。""" from app.services.rag import llm - key = require_deepseek_key(db, user.id) + provided = (body.deepseek_api_key or "").strip() if body else "" + key = provided or require_deepseek_key(db, user.id) db.rollback() try: reply = llm.chat_text( @@ -146,14 +151,19 @@ def test_deepseek(user: User = Depends(get_current_user), db: Session = Depends( @router.post("/model-settings/test-mineru", summary="测试 MinerU 连接与鉴权(不验证文件解析)") -def test_mineru(user: User = Depends(get_current_user), db: Session = Depends(get_db)): - """只读验证已保存 MinerU 配置的连接与鉴权,不验证额度或实际文件解析。 +def test_mineru( + body: ModelTestBody | None = None, + user: User = Depends(get_current_user), + db: Session = Depends(get_db), +): + """只读验证 MinerU 配置的连接与鉴权;body 提供输入值时优先测试该值,不落库。 严格校验 HTTP、JSON 与业务状态,仅将明确成功或官方找不到探测任务视为通过。 """ from app.services import mineru - token = get_effective_mineru_token(db, user.id) + provided = (body.mineru_token or "").strip() if body else "" + token = provided or get_effective_mineru_token(db, user.id) if not token: raise AppError("MINERU_TOKEN_MISSING", "请先填写 MinerU Token", status_code=400) ok, detail = mineru.ping_token(token) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 740811a..759b3e4 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -1,7 +1,7 @@ """导入全部模型,供 Alembic autogenerate 与 create_all 使用。""" from app.models.auth import AuthProof, AuthSession, EmailChange, RefreshUse from app.models.bank import Bank, BankMember, Document, DocumentChunk -from app.models.chat import ChatMessage, ChatSession +from app.models.chat import ChatMessage, ChatRequest, ChatSession from app.models.deletion import DeletionOperation from app.models.favorite import Favorite, FavoriteGroup from app.models.generation_task import GenerationTask @@ -25,7 +25,7 @@ __all__ = [ "AuthProof", "AuthSession", "EmailChange", "RefreshUse", "Bank", "BankMember", "Document", "DocumentChunk", - "ChatMessage", "ChatSession", + "ChatMessage", "ChatRequest", "ChatSession", "DeletionOperation", "GenerationTask", "Favorite", "FavoriteGroup", "Notification", diff --git a/backend/app/models/bank.py b/backend/app/models/bank.py index b63ba71..62abf18 100644 --- a/backend/app/models/bank.py +++ b/backend/app/models/bank.py @@ -14,7 +14,7 @@ class Bank(Base, TimestampMixin): id: Mapped[StrPK] name: Mapped[str] = mapped_column(String(64), nullable=False) - code: Mapped[str] = mapped_column(String(32), unique=True, nullable=False) # TK + 年份 + 序号 + code: Mapped[str] = mapped_column(String(32), unique=True, nullable=False) # TK + 8 位随机字符,共 10 位 creator_id: Mapped[str] = mapped_column(String(40), ForeignKey("users.id"), nullable=False) admin_level: Mapped[str] = mapped_column(String(16), default="super", nullable=False) # 历史兼容字段,不参与成员权限判断 capacity: Mapped[int] = mapped_column(default=200, nullable=False) diff --git a/backend/app/models/chat.py b/backend/app/models/chat.py index 5402167..c9479a0 100644 --- a/backend/app/models/chat.py +++ b/backend/app/models/chat.py @@ -1,6 +1,6 @@ """对话会话与消息。""" from datetime import datetime -from typing import Optional +from typing import Literal, Optional from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text from sqlalchemy.orm import Mapped, mapped_column @@ -46,3 +46,22 @@ class ChatMessage(Base): content: Mapped[str] = mapped_column(Text, nullable=False) batch_id: Mapped[Optional[str]] = mapped_column(String(40)) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, nullable=False) + + +ChatRequestStatus = Literal["running", "canceled", "done", "failed", "interrupted"] + + +class ChatRequest(Base): + """持久化客户端轮次的取消、发布与执行退出事实。""" + + __tablename__ = "chat_requests" + + session_id: Mapped[str] = mapped_column( + String(40), ForeignKey("chat_sessions.id", ondelete="CASCADE"), primary_key=True, + ) + request_id: Mapped[str] = mapped_column(String(36), primary_key=True) + run_id: Mapped[str | None] = mapped_column(String(40), unique=True) + status: Mapped[ChatRequestStatus] = mapped_column(String(16), nullable=False) + execution_finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + batch_id: Mapped[str | None] = mapped_column(String(40)) + result_json: Mapped[str | None] = mapped_column(Text) diff --git a/backend/app/models/space.py b/backend/app/models/space.py index 160b539..3a1fbb3 100644 --- a/backend/app/models/space.py +++ b/backend/app/models/space.py @@ -13,7 +13,7 @@ class StudySpace(Base, TimestampMixin): id: Mapped[StrPK] name: Mapped[str] = mapped_column(String(64), nullable=False) - code: Mapped[str] = mapped_column(String(32), unique=True, nullable=False) # SP + 96 位随机加入码 + code: Mapped[str] = mapped_column(String(32), unique=True, nullable=False) # SP + 8 位随机字符,共 10 位 creator_id: Mapped[str] = mapped_column(String(40), ForeignKey("users.id"), nullable=False) capacity: Mapped[int] = mapped_column(nullable=False) # 1~500 status: Mapped[str] = mapped_column(String(16), default="active", nullable=False) # active / dissolved diff --git a/backend/app/schemas/api.py b/backend/app/schemas/api.py index 0a6b761..9a9cf2d 100644 --- a/backend/app/schemas/api.py +++ b/backend/app/schemas/api.py @@ -7,13 +7,15 @@ from pydantic import BaseModel, Field, field_validator, model_validator -from app.schemas.question import Question +from app.schemas.question import Difficulty, Question, QuestionType class TypeCountBody(BaseModel): type: str = Field(pattern="^(single|multiple|judge|blank|compute|essay)$") # 高压长任务:单题型上限放宽到 100,与 TypeCount 一致 count: int = Field(ge=1, le=100) + # 题型级难度;缺省回退整体 difficulty + difficulty: str | None = Field(default=None, pattern="^(低|中|高|地狱)$") class GenerateStartBody(BaseModel): @@ -139,6 +141,7 @@ class ChatSessionDetailResponse(BaseModel): class ChatMessageBody(BaseModel): + request_id: UUID | None = None message: str = Field( max_length=2048, description="消息文本;仅发送图片时可为空,文本与图片不可同时为空", ) @@ -185,6 +188,65 @@ def require_content(self) -> Self: return self +class ChatOperationPreview(BaseModel): + """已发布的操作确认预览。""" + + id: str + action: Literal["delete", "update"] + entity: str + entity_label: str + affected: int + samples: list[str] + explanation: str + + +class ChatSavedQuestion(BaseModel): + """题库中当前保存的对话题目。""" + + id: str + type: QuestionType + score: int + difficulty: Difficulty + difficulty_score: float + difficulty_review: dict[str, object] | None + stem: str + options: list[dict[str, object]] + answer: str + analysis: str + knowledge_point: str + starred: bool + favorite_group_id: str | None + doc_name: str + bank_id: str + document_id: str + batch_id: str + created_at: datetime + + +class ChatMessageResponse(BaseModel): + """消息接口与状态查询共用的已发布回复。""" + + reply: str + questions: list[ChatSavedQuestion | Question] + done: bool + batch_id: str | None + slot_state: dict[str, object] + kind: Literal["reply", "mode_mismatch", "mode_confirm"] + mode: Literal["generate", "creative", "qa", "data"] + mode_changed: bool + suggested_template: Literal["generate", "creative", "qa", "data", "none"] | None + confirm: ChatOperationPreview | None + + +class ChatRequestResponse(BaseModel): + """指定轮次的业务状态及执行退出事实。""" + + status: Literal["running", "canceled", "done", "failed", "interrupted"] + execution_finished: bool + batch_id: str | None + result: ChatMessageResponse | None + + class ChatConfirmBody(BaseModel): """数据管理高危操作的确认:接受执行 / 拒绝取消。""" diff --git a/backend/app/schemas/auth.py b/backend/app/schemas/auth.py index 2551e7a..8fa24be 100644 --- a/backend/app/schemas/auth.py +++ b/backend/app/schemas/auth.py @@ -110,6 +110,13 @@ class ModelSettingsBody(BaseModel): mineru_token: str | None = Field(default=None, max_length=128) +class ModelTestBody(BaseModel): + """连接测试的可选输入值;提供时优先测试该值,不落库。""" + + deepseek_api_key: str | None = Field(default=None, max_length=128) + mineru_token: str | None = Field(default=None, max_length=128) + + class AuthConfig(BaseModel): """公开认证能力与双提交 CSRF 令牌,不包含服务端密钥。""" diff --git a/backend/app/schemas/question.py b/backend/app/schemas/question.py index 61fdace..2aab371 100644 --- a/backend/app/schemas/question.py +++ b/backend/app/schemas/question.py @@ -132,6 +132,8 @@ class TypeCount(BaseModel): type: QuestionType # 高压长任务:单题型上限放宽到 100,由规划层拆批执行 count: int = Field(ge=1, le=100) + # 题型级难度;None 时回退全局 params.difficulty + difficulty: Difficulty | None = None class GenerateParams(BaseModel): diff --git a/backend/app/services/attempts.py b/backend/app/services/attempts.py index 7ee556b..55a545d 100644 --- a/backend/app/services/attempts.py +++ b/backend/app/services/attempts.py @@ -320,7 +320,7 @@ def submit_attempt( for row in rows ) if needs_llm and not api_key: - raise AppError("DEEPSEEK_KEY_MISSING", "主观题批卷需要 DeepSeek API Key,请到设置 → 模型与服务中填写", 400) + raise AppError("DEEPSEEK_KEY_MISSING", "主观题批卷需要 DeepSeek API Key,请到个人中心 → API 配置中填写", 400) attempt.status = "grading" attempt.grading_run_id = run_id db.commit() diff --git a/backend/app/services/banks.py b/backend/app/services/banks.py index 3e1a075..0c507c2 100644 --- a/backend/app/services/banks.py +++ b/backend/app/services/banks.py @@ -1,9 +1,9 @@ """题库业务:编号生成、列表载荷、成员操作、删除清理。""" from collections.abc import Callable -from datetime import datetime, timezone import json import logging from pathlib import Path +import secrets import sqlite3 from time import sleep from typing import TypeVar @@ -87,17 +87,15 @@ def _delete_transaction(db: Session, action: Callable[[RuntimeSnapshot], T]) -> raise AppError("DATABASE_BUSY", "数据库繁忙,请稍后重试删除", 503) +CODE_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + def generate_bank_code(db: Session) -> str: - """TK + 年份 + 4 位序号;序号按当年已有题库数递增,冲突时步进重试。""" - year = datetime.now(timezone.utc).year - prefix = f"TK{year}" - base = db.query(func.count(Bank.id)).filter(Bank.code.like(f"{prefix}%")).scalar() or 0 - seq = base + 1 + """10 位随机编号(TK 前缀 + 8 位随机字符),冲突时重试。""" while True: - code = f"{prefix}{seq:04d}" + code = "TK" + "".join(secrets.choice(CODE_ALPHABET) for _ in range(8)) if not db.query(Bank.id).filter(Bank.code == code).first(): return code - seq += 1 def member_count(db: Session, bank_id: str) -> int: diff --git a/backend/app/services/generation.py b/backend/app/services/generation.py index fd2471f..92e5238 100644 --- a/backend/app/services/generation.py +++ b/backend/app/services/generation.py @@ -14,7 +14,7 @@ from app.deps import resolve_bank_access from app.errors import AppError from app.models import Document, GenerationBatch, OpsRun, Question, User -from app.models.chat import ChatSession +from app.models.chat import ChatRequest, ChatSession from app.models.base import new_id, utcnow from app.models.generation_task import GenerationTask from app.models.ops_run import RunEntrypoint, RunErrorCode, RunStatus @@ -416,7 +416,13 @@ def build_params(body: GenerateStartBody) -> GenerateParams: return GenerateParams( kb_id=bank_id, doc_id=document_id, - types=[TypeCount(type=QuestionType(t.type), count=t.count) for t in body.types], + types=[ + TypeCount( + type=QuestionType(t.type), count=t.count, + difficulty=Difficulty(t.difficulty) if t.difficulty else None, + ) + for t in body.types + ], difficulty=Difficulty(body.difficulty), source_mode=body.source_mode, scope=body.scope, @@ -743,6 +749,12 @@ def recover_interrupted_generation() -> None: db.query(ChatSession).filter(ChatSession.run_status == "running").update({ "run_status": "interrupted", "run_stage": "服务重启,请重新发送消息", }, synchronize_session=False) + db.query(ChatRequest).filter(ChatRequest.execution_finished_at.is_(None)).update({ + "status": case( + (ChatRequest.status == "running", "interrupted"), else_=ChatRequest.status, + ), + "execution_finished_at": utcnow(), + }, synchronize_session=False) db.commit() for task in tasks: release_lock(task.user_id, f"{task.id}:{task.run_id}") diff --git a/backend/app/services/grading.py b/backend/app/services/grading.py index e41247f..4292a72 100644 --- a/backend/app/services/grading.py +++ b/backend/app/services/grading.py @@ -53,7 +53,7 @@ def grade_subjective(pq: PaperQuestion, text: str, api_key: str | None) -> tuple if not api_key: raise AppError( "DEEPSEEK_KEY_MISSING", - "主观题批卷需要 DeepSeek API Key,请到设置 → 模型与服务中填写", + "主观题批卷需要 DeepSeek API Key,请到个人中心 → API 配置中填写", status_code=400, ) try: diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.py index d9c147e..179d57a 100644 --- a/backend/app/services/model_settings.py +++ b/backend/app/services/model_settings.py @@ -41,7 +41,7 @@ def require_deepseek_key(db: Session, user_id: str) -> str: if not key: raise AppError( "DEEPSEEK_KEY_MISSING", - "尚未配置 DeepSeek API Key,请到设置 → 模型与服务中填写", + "尚未配置 DeepSeek API Key,请到个人中心 → API 配置中填写", status_code=400, ) return key diff --git a/backend/app/services/question_review.py b/backend/app/services/question_review.py index bf20634..bac9fc9 100644 --- a/backend/app/services/question_review.py +++ b/backend/app/services/question_review.py @@ -533,7 +533,10 @@ def _regen( ) -> list[Question]: """按题型补出 count 道,避免与已保留题目重复。""" check_cancellation(cancel_check) - sub = params.model_copy(update={"types": [TypeCount(type=qtype, count=count)]}) + sub_diff = next( + (tc.difficulty for tc in params.types if tc.type == qtype and tc.difficulty), None, + ) + sub = params.model_copy(update={"types": [TypeCount(type=qtype, count=count, difficulty=sub_diff)]}) return question_gen.generate_questions( sub, doc_name, @@ -925,8 +928,9 @@ def report(percent: int, stage: str) -> None: progress(percent, stage) check_cancellation(cancel_check) - target = params.difficulty scope = params.scope or "" + # 题型级难度优先于整体难度档:同批不同题型可要求不同目标档 + type_difficulty = {tc.type: tc.difficulty for tc in params.types if tc.difficulty} if db.in_transaction() or db.new or db.dirty or db.deleted: # 连已 flush 的变更也通过活动事务拒绝,不能只检查 new/dirty/deleted 后 rollback。 raise InvalidRequestError( @@ -959,6 +963,7 @@ def report(percent: int, stage: str) -> None: if not items: continue target_count = requested.get(qtype, len(items)) + target = type_difficulty.get(qtype, params.difficulty) report(78, f"正在排查重复题目({done + 1}/{total})") kept, dropped = run_checked( diff --git a/backend/app/services/rag/chat_flow.py b/backend/app/services/rag/chat_flow.py index 7961cdc..8c96c37 100644 --- a/backend/app/services/rag/chat_flow.py +++ b/backend/app/services/rag/chat_flow.py @@ -2,13 +2,14 @@ from typing import Callable from app.models.ops_run import RunErrorCode -from app.schemas.question import GenerateParams, Question, QuestionType, TypeCount +from app.schemas.question import Difficulty, GenerateParams, Question, QuestionType, TypeCount from app.services.generation_cancellation import GenerationCanceled, cancellation_kwargs from app.services.rag.llm import friendly_error from app.services.rag.prompts import CREATIVE_SYSTEM_EXTRA from app.services.rag.question_gen import NeedConfirmError, generate_questions from app.services.rag.slots import ( - build_followup, build_params, extract_slots, merge_slots, missing_keys, + build_followup, build_natural_followup, build_params, extract_slots, merge_slots, + missing_keys, ) DONE_REPLY = "题目已生成完成,共 {n} 道,已同步到「题目预览」标签页。还需要生成其他题型吗?" @@ -93,7 +94,9 @@ def report(percent: int, stage: str) -> None: )) missing = missing_keys(state) if missing: - return {"reply": build_followup(missing, state), "slot_state": state, + reply = (build_natural_followup(message, state, missing, api_key=api_key) + or build_followup(missing, state)) + return {"reply": reply, "slot_state": state, "questions": [], "done": False} _guard(cancel_check) @@ -115,6 +118,7 @@ def gen_progress(percent: int, stage: str) -> None: doc_name, scope=scope, mixed_difficulty=bool(state.get("mixed_difficulty")), + difficulty_note=str(state.get("difficulty_note") or ""), existing_stems=existing_stems, api_key=api_key, hyde_text=hyde_text, @@ -246,8 +250,11 @@ def review_with_refill( from app.services.question_review import ReviewStats, _norm as normalize quota: dict[QuestionType, int] = {} + type_difficulty: dict[QuestionType, Difficulty] = {} for item in params.types: quota[item.type] = quota.get(item.type, 0) + item.count + if item.difficulty: + type_difficulty[item.type] = item.difficulty counts = dict.fromkeys(quota, 0) accepted: list[Question] = [] avoid = list(dict[str, None].fromkeys((existing_stems or []) + params.existing_stems)) @@ -269,7 +276,8 @@ def report(percent: int, stage: str) -> None: report(78 + round_no * 8, "正在审核题目" if not round_no else "正在审核补齐题目") review_params = params.model_copy(update={ "existing_stems": list(avoid), - "types": [TypeCount(type=kind, count=target - counts[kind]) + "types": [TypeCount(type=kind, count=target - counts[kind], + difficulty=type_difficulty.get(kind)) for kind, target in quota.items() if counts[kind] < target], }) passed, current_stats = review_fn(pool, review_params, list(avoid)) @@ -291,7 +299,8 @@ def report(percent: int, stage: str) -> None: if normalize(question.stem) not in seen: seen.add(normalize(question.stem)) avoid.append(question.stem) - deficits = [TypeCount(type=kind, count=target - counts[kind]) + deficits = [TypeCount(type=kind, count=target - counts[kind], + difficulty=type_difficulty.get(kind)) for kind, target in quota.items() if counts[kind] < target] if not deficits or len(accepted) >= requested or round_no == MAX_REFILL_ROUNDS: break diff --git a/backend/app/services/rag/llm.py b/backend/app/services/rag/llm.py index 50f232d..38f1aab 100644 --- a/backend/app/services/rag/llm.py +++ b/backend/app/services/rag/llm.py @@ -30,11 +30,11 @@ class LLMError(RuntimeError): """模型调用失败;只有白名单中的固定提示可直接公开。""" -_MISSING_KEY = "DeepSeek API Key 未配置:请到设置 → 模型与服务中填写" +_MISSING_KEY = "DeepSeek API Key 未配置:请到个人中心 → API 配置中填写" _INVALID_JSON = "模型返回的 JSON 无法解析,请重试" _GENERIC_ERROR = "模型调用失败,请稍后重试" -_BALANCE_ERROR = "DeepSeek 账户余额不足,请到设置 → 模型与服务更换密钥或充值后重试" -_AUTH_ERROR = "DeepSeek API Key 无效,请到设置 → 模型与服务检查密钥" +_BALANCE_ERROR = "DeepSeek 账户余额不足,请到个人中心 → API 配置更换密钥或充值后重试" +_AUTH_ERROR = "DeepSeek API Key 无效,请到个人中心 → API 配置检查密钥" _RATE_ERROR = "模型接口请求过于频繁,请等一两分钟再试" _TIMEOUT_ERROR = "模型响应超时,请稍后重试" _STATUS_ERRORS = {401: _AUTH_ERROR, 402: _BALANCE_ERROR, 429: _RATE_ERROR} diff --git a/backend/app/services/rag/prompts.py b/backend/app/services/rag/prompts.py index 330b14e..b1b6a35 100644 --- a/backend/app/services/rag/prompts.py +++ b/backend/app/services/rag/prompts.py @@ -197,28 +197,50 @@ "等等,", "稍等", "修正一下", "这里错了", "我重算", "hmm", "wait,", ) -SLOT_EXTRACT_SYSTEM = """你是出题助手的信息抽取模块。从用户消息(及图片)中抽取本次出题意图的槽位, -只输出 JSON,格式固定为: +SLOT_EXTRACT_SYSTEM = """你是出题助手的信息抽取模块。把用户消息(及图片)里的出题需求填入下面的模板, +只输出 JSON,字段固定为: { - "types": [{"type": "single|multiple|judge|blank|compute|essay", "count": 正整数或 null}], - "count": 正整数或 null, - "scope": "知识点或章节范围(原文字符串)或 null", - "difficulty": "低|中|高|地狱 或 null", + "scope": "知识点或章节范围(保留用户原文,如「线性代数知识点总结」)或 null", + "types": [{"type": "single|multiple|judge|blank|compute|essay", + "count": 正整数或 null, + "difficulty": "该题型的难度(同义词先归一,见下)或 null"}], + "count": 总题量(仅在用户给了总数、未按题型分别说明时填写,否则 null), + "difficulty": "整体难度:用户未按题型区分难度时填写(低|中|高|地狱),否则 null", "mixed_difficulty": true/false, + "source_mode": "original|variant_data|variant_context|new 或 null", "image_note": "若用户上传了图片,一句话描述图片中的题型结构与设问方式,否则 null" } -用户未提及的字段一律填 null 或空数组,禁止猜测,禁止填默认值。 -短期记忆是最近几轮对话原文:结合它理解指代(如"再来一批""换成难的""按刚才的数量"); -记忆中已确认的题型数量难度,除非本次明确更改,否则继续沿用;记忆中没有的信息不要编造。 -"count" 只在用户给了总题量、但没有按题型分别说明时填写;已经按题型说清数量时, -各 types 项填自己的 count,"count" 填 null。 -题型对应:说"选择题"→single,"多选"→multiple,"判断"→judge,"填空"→blank, -"计算"→compute,"简答/解答"→essay。 -多题型分别计数:如"5道选择题和3道判断题"→ -"types": [{"type":"single","count":5},{"type":"judge","count":3}],"count": null。 -只说了题型没说数量时,该题型 count 必须是 null,不要自己补 5 或任何数字。 +填写规则: +1 题型映射:选择题→single,多选→multiple,判断→judge,填空→blank,计算→compute,简答/解答→essay。 +2 难度归一:简单/容易/基础/偏低→低,中等/常规→中,难/很难/高难/较难/困难/偏难→高,地狱→地狱。 +3 用户按题型分别说明难度时(如 5 道低难度选择题、2 道高难度填空题、4 道中难度计算题), + 把每项写进 types 对应条目的 difficulty,此时整体 difficulty 填 null、mixed_difficulty 填 true。 +4 用户只给一个难度档时写入整体 difficulty,types 各条目 difficulty 填 null,mixed_difficulty 填 false。 +5 用户对同一题型给了多个难度档(如 3 道选择题、难度分别是简单中等高难)时, + types 该条目的 count 照填、difficulty 填 null,整体 difficulty 原样保留该多档描述, + mixed_difficulty 填 true。 +6 只说了题型没说数量时该题型 count 填 null,禁止猜测;用户未提及的字段一律 null,禁止编造。 +7 短期记忆是最近几轮对话原文:结合它理解指代(如"再来一批""换成难的""按刚才的数量"); + 记忆中已确认的题型、数量、难度,除非本次明确更改,否则原样沿用;记忆中没有的信息不要编造。 + 记忆中的难度是多档描述(如「低、中、高」)时必须原样保留到 difficulty 并继续标记 + mixed_difficulty=true,禁止压缩成其中某一档(如只取「高」); + 当前消息没有新的难度表述时不得自行挑选档位。 +8 多题型分别计数:如 5 道选择题和 3 道判断题 → + "types": [{"type":"single","count":5},{"type":"judge","count":3}],"count" 填 null。 +9 source_mode 只在用户明确要求原题/改数据/换背景/全新时填写,未提及一律 null。 只输出 JSON。""" +FOLLOWUP_SYSTEM = """你是数学出题助手的追问模块。用户的出题要求还缺少一部分信息, +你要用一到两句自然的中文把缺的信息问清楚。 + +要求: +1 只追问【还缺少的信息】里列出的内容;已确认的信息不要重复问,也不要让用户复述。 +2 语气自然友好,像助教在对话里随手一问,不要写编号列表,不要用「您好」这类客套开头。 +3 涉及可选值时顺手给提示:题型有选择题、多选题、判断题、填空题、计算题、简答题; + 难度分为低、中、高、地狱;数量按每种题型分别说明。 +4 不要替用户决定缺的信息,也不要输出追问以外的内容。 +5 直接输出追问文本,不加引号、前缀或任何解释。""" + HYDE_SYSTEM = """你是高等数学教材的编写助手。根据给定的知识点或章节范围, 撰写一段 200 到 400 字的讲解性文字,内容要像教材中能覆盖该知识点的段落: 包含定义、关键定理或公式(用 $...$ 包裹的 LaTeX 表示)、典型方法与适用条件。 diff --git a/backend/app/services/rag/question_gen.py b/backend/app/services/rag/question_gen.py index 214b131..945253f 100644 --- a/backend/app/services/rag/question_gen.py +++ b/backend/app/services/rag/question_gen.py @@ -295,11 +295,13 @@ def _gen_batch( hits: list[dict], directive: str, hint: str = "", + difficulty_note: str = "", cancel_check: Callable[[], None] | None = None, ) -> list[Question]: """一次生成 count 道题:流式输出 + 滚动校验,Schema 失败带错误信息重试一次。""" check_cancellation(cancel_check) type_label = TYPE_LABELS[tc.type] + difficulty = tc.difficulty or params.difficulty extra = f"- 知识点范围:{scope}" if scope else "" if scope and tc.count >= HIGH_PRESSURE_THRESHOLD: extra += ( @@ -317,7 +319,11 @@ def _gen_batch( "禁止同一模板换数字,避免被查重判为重复" ) if mixed_difficulty: - extra += "\n- 难度分布:约三分之一达到高难度,其余为中等难度" + distribution = ( + f"{difficulty_note},各题难度按该描述的比例分配,不得全部同一档" + if difficulty_note else "约三分之一达到高难度,其余为中等难度" + ) + extra += f"\n- 难度分布:{distribution}" if directive: extra += "\n" + directive if avoid_snapshot: @@ -329,7 +335,7 @@ def _gen_batch( context=_build_context(hits), type_label=type_label, count=count, - difficulty=params.difficulty.value, + difficulty=difficulty.value, source_mode=SOURCE_LABELS.get(params.source_mode, params.source_mode), score=DEFAULT_SCORES.get(tc.type, 5), extra=extra, @@ -382,7 +388,7 @@ def _gen_batch( continue # 题型不符直接丢弃 q.id = f"q-{uuid.uuid4().hex[:10]}" q.score = DEFAULT_SCORES.get(tc.type, 5) - q.difficulty = params.difficulty + q.difficulty = difficulty q.docName = doc_name q.answer = "" q.analysis = "" @@ -484,6 +490,7 @@ def _gen_for_type( retrieve_fn: RetrieveFn | None = None, report: Callable[[float, str], None] | None = None, directive: str = "", + difficulty_note: str = "", cancel_check: Callable[[], None] | None = None, ) -> list[Question]: """生成单个题型的题目。report(frac, stage) 上报该 agent 的内部完成度(0~1)与阶段文案。 @@ -522,7 +529,7 @@ def _gen_for_type( if report: report(0.06, f"正在规划「{type_label}」的考点分布") points = _plan_points( - scope, type_label, params.difficulty.value, tc.count, hits, api_key, + scope, type_label, (tc.difficulty or params.difficulty).value, tc.count, hits, api_key, **cancellation_kwargs(cancel_check), ) @@ -548,9 +555,11 @@ def _gen_for_type( pool.submit( run_checked, cancel_check, _gen_batch, tc, params, doc_name, scope, size, snapshot, - mixed_difficulty, api_key, hits, directive, + # 题型自带难度时按单档命题,混合难度分布只作用于未单独指定难度的题型 + mixed_difficulty and tc.difficulty is None, api_key, hits, directive, # 按已完成题数取考点,补齐轮次接着往后排,避免重复同一考点 points[len(collected) + index] if len(collected) + index < len(points) else "", + difficulty_note=difficulty_note, **cancellation_kwargs(cancel_check), ) for index, size in enumerate(batch_sizes) @@ -594,6 +603,7 @@ def generate_questions( doc_name: str, scope: str | None = None, mixed_difficulty: bool = False, + difficulty_note: str = "", existing_stems: list[str] | None = None, progress_cb: ProgressCB | None = None, api_key: str | None = None, @@ -653,6 +663,7 @@ def run_one(idx: int, tc) -> None: retrieve_fn=retrieve_fn, report=make_report(idx), directive=directive, + difficulty_note=difficulty_note, **cancellation_kwargs(cancel_check), ) check_cancellation(cancel_check) diff --git a/backend/app/services/rag/slots.py b/backend/app/services/rag/slots.py index 8640e07..e8dd890 100644 --- a/backend/app/services/rag/slots.py +++ b/backend/app/services/rag/slots.py @@ -1,14 +1,17 @@ """对话出题的槽位状态机:抽取 → 合并 → 缺啥问啥。 -追问文案用固定模板,保证换行、按点、带序号; -抽取交给模型(JSON 输出),只做结构化信息提取不做回复生成。 -缺槽一律追问,不用默认值补齐。 +抽取交给模型(JSON 输出),只做结构化信息提取;缺槽时先让模型生成自然追问, +失败再回退固定模板。缺槽一律追问,不用默认值补齐。 """ +import logging import math +import re from app.schemas.question import Difficulty, GenerateParams, QuestionType, TypeCount -from app.services.rag.llm import chat_json -from app.services.rag.prompts import SLOT_EXTRACT_SYSTEM +from app.services.rag.llm import chat_json, chat_text +from app.services.rag.prompts import FOLLOWUP_SYSTEM, SLOT_EXTRACT_SYSTEM + +logger = logging.getLogger("app.rag.slots") # 槽位检查顺序即追问顺序。题目来源已不再追问:知识库只存知识点,没有原题可还原。 SLOT_ORDER = ["types", "count", "difficulty", "scope"] @@ -20,6 +23,13 @@ "全新": "new", "新题": "new", "全新的": "new", } DIFFICULTY_ALIASES = {"简单": "低", "容易": "低", "基础": "低", "中等": "中", "常规": "中", "难": "高", "很难": "高", "地狱": "地狱"} +# 子串扫描用:按长度降序匹配并消耗原文,避免「中等」里的「中」、「高难」里的「难」被重复命中 +DIFFICULTY_TOKENS = ( + ("地狱", "地狱"), ("简单", "低"), ("容易", "低"), ("偏易", "低"), ("较易", "低"), + ("基础", "低"), ("中等", "中"), ("中档", "中"), ("常规", "中"), ("高难", "高"), + ("较难", "高"), ("很难", "高"), ("困难", "高"), ("偏难", "高"), ("难题", "高"), + ("难", "高"), ("高", "高"), ("中", "中"), ("低", "低"), +) TYPE_ALIASES = {"选择": "single", "单选": "single", "多选": "multiple", "判断": "judge", "填空": "blank", "计算": "compute", "简答": "essay", "解答": "essay"} TYPE_LABELS = {"single": "选择题", "multiple": "多选题", "judge": "判断题", "blank": "填空题", "compute": "计算题", "essay": "简答题"} @@ -68,21 +78,21 @@ def _norm_count(raw: object) -> int | None: def _norm_types(raw) -> list[dict] | None: - """把抽取结果归一化为 [{type, count}],非法项丢弃。兼容顶层 type/count 旧写法。""" + """把抽取结果归一化为 [{type, count, difficulty}],非法项丢弃。兼容顶层 type/count 旧写法。""" items = raw if isinstance(raw, list) else [raw] if isinstance(raw, dict) else [] out: list[dict] = [] for item in items: if not isinstance(item, dict): - t_raw, c_raw = item, None + t_raw, c_raw, d_raw = item, None, None else: - t_raw, c_raw = item.get("type"), item.get("count") + t_raw, c_raw, d_raw = item.get("type"), item.get("count"), item.get("difficulty") t = TYPE_ALIASES.get(str(t_raw).strip(), str(t_raw).strip() if t_raw else None) try: QuestionType(t) except ValueError: continue count = _norm_count(c_raw) - out.append({"type": t, "count": count}) + out.append({"type": t, "count": count, "difficulty": _norm_difficulty(d_raw)}) return out or None @@ -105,11 +115,33 @@ def _norm_source(raw) -> str | None: return SOURCE_ALIASES.get(s, s if s in ("original", "variant_data", "variant_context", "new") else None) +def _norm_single(raw: str) -> str | None: + """归一化单个难度描述段;先查精确别名,再剥修饰词后按长度降序扫同义词。""" + s = raw.strip() + direct = DIFFICULTY_ALIASES.get(s, s if s in ("低", "中", "高", "地狱") else None) + if direct: + return direct + cleaned = s.removeprefix("难度").strip("的度请帮我要想出题生成一点些") + for token, level in sorted(DIFFICULTY_TOKENS, key=lambda pair: -len(pair[0])): + if token in cleaned: + return level + return None + + def _norm_difficulty(raw) -> str | None: if not raw: return None - s = str(raw).strip() - return DIFFICULTY_ALIASES.get(s, s if s in ("低", "中", "高", "地狱") else None) + return _norm_single(str(raw).strip()) + + +def _levels_in(text: str) -> list[str]: + """按分隔符切段逐段归一化,返回去重后的难度档序列,顺序即出现顺序。""" + segments = [seg for seg in re.split(r"[,、,;;\s]+|[和与]", str(text)) if seg.strip()] + levels = [] + for segment in segments: + if level := _norm_single(segment): + levels.append(level) + return list(dict.fromkeys(levels)) def merge_slots(state: dict, extracted: dict) -> dict: @@ -125,14 +157,26 @@ def merge_slots(state: dict, extracted: dict) -> dict: if old: if t["count"]: old["count"] = t["count"] + if t["difficulty"]: + old["difficulty"] = t["difficulty"] else: - existing[t["type"]] = {"type": t["type"], "count": t["count"]} + existing[t["type"]] = {"type": t["type"], "count": t["count"], + "difficulty": t["difficulty"]} new["types"] = list(existing.values()) if v := _norm_source(extracted.get("source_mode")): new["source_mode"] = v - if v := _norm_difficulty(extracted.get("difficulty")): - new["difficulty"] = v - new.pop("mixed_difficulty", None) + raw_diff = str(extracted.get("difficulty") or "").strip() + if raw_diff: + levels = _levels_in(raw_diff) + if len(set(levels)) >= 2: + # 用户一次说了多个难度档:按混合难度处理,保留原始描述供生成指令使用,不再追问 + new["mixed_difficulty"] = True + new["difficulty_note"] = raw_diff[:120] + new["difficulty"] = "中" if "中" in levels else levels[-1] + elif v := _norm_difficulty(raw_diff): + new["difficulty"] = v + new.pop("mixed_difficulty", None) + new.pop("difficulty_note", None) if extracted.get("mixed_difficulty") and not new.get("difficulty"): new["mixed_difficulty"] = True if v := extracted.get("scope"): @@ -173,6 +217,16 @@ def _counts_complete(state: dict) -> bool: ) +def _difficulty_complete(state: dict) -> bool: + """整体难度与题型级难度任一存在即视为已给;混合难度场景整体难度档必被写入。""" + if _norm_difficulty(state.get("difficulty")): + return True + return any( + isinstance(t, dict) and _norm_difficulty(t.get("difficulty")) + for t in state.get("types") or [] + ) + + def missing_keys(state: dict) -> list[str]: missing: list[str] = [] for key in SLOT_ORDER: @@ -184,7 +238,7 @@ def missing_keys(state: dict) -> list[str]: missing.append(key) elif key == "scope" and not str(state.get(key) or "").strip(): missing.append(key) - elif key == "difficulty" and _norm_difficulty(state.get(key)) is None: + elif key == "difficulty" and not _difficulty_complete(state): missing.append(key) return missing @@ -223,25 +277,96 @@ def build_followup(missing: list[str], state: dict | None = None) -> str: return "\n".join([FOLLOWUP_HEAD, *numbered, FOLLOWUP_TAIL]) +def _describe_state(state: dict) -> str: + types = [] + for t in state.get("types") or []: + if not isinstance(t, dict) or t.get("type") not in TYPE_LABELS: + continue + label = TYPE_LABELS[t["type"]] + count = _norm_count(t.get("count")) + if count is not None: + label += f" {count} 道" + diff = _norm_difficulty(t.get("difficulty")) + if diff: + label += f"(难度{diff})" + types.append(label) + known = [] + if types: + known.append("题型:" + "、".join(types)) + total = _norm_count(state.get("total_count")) + if total is not None: + known.append(f"总题量 {total} 道") + diff = _norm_difficulty(state.get("difficulty")) + if diff and not state.get("mixed_difficulty"): + known.append(f"难度:{diff}") + if state.get("mixed_difficulty") and state.get("difficulty_note"): + known.append(f"难度分布:{state['difficulty_note']}") + if str(state.get("scope") or "").strip(): + known.append(f"知识点范围:{state['scope']}") + return ";".join(known) if known else "暂无" + + +def build_natural_followup( + message: str, state: dict, missing: list[str], api_key: str | None = None, +) -> str | None: + """让模型结合上下文生成自然追问;未配 key、失败或输出为空时返回 None, + 由调用方回退固定模板。""" + if not api_key: + return None + need = ";".join( + _count_line(state) if key == "count" else FOLLOWUP_LINES[key] + for key in SLOT_ORDER if key in missing + ) + prompt = ( + f"【当前用户消息】\n{message}\n\n【已确认的出题要求】\n{_describe_state(state)}" + f"\n\n【还缺少的信息】\n{need}" + ) + try: + text = chat_text( + [ + {"role": "system", "content": FOLLOWUP_SYSTEM}, + {"role": "user", "content": prompt}, + ], + api_key=api_key, temperature=0.4, max_tokens=200, thinking_off=True, + ) + except Exception as exc: # 追问是辅助路径,失败回退模板并记日志 + logger.warning("自然追问生成失败,回退模板:%s", exc) + return None + return (text or "").strip() or None + + def build_params( state: dict, bank_id: str, document_id: str, ) -> tuple[GenerateParams, str]: - """从完整槽位构造 GenerateParams 与 scope。数量必须由用户给出。""" + """从完整槽位构造 GenerateParams 与 scope。数量必须由用户给出。 + + 题型级难度优先:types 条目自带难度时写入 TypeCount.difficulty, + 整体难度缺省时取第一个题型难度,再缺省回退中档。 + """ missing = missing_keys(state) if missing: raise ValueError("出题信息不完整:" + "、".join(missing)) types = [] + type_diffs: list[str | None] = [] for item in state["types"]: count = _norm_count(item.get("count")) if count is None: - raise ValueError("每个题型的数量必须是 1–20 的整数") - types.append(TypeCount(type=QuestionType(item["type"]), count=count)) - + raise ValueError("每个题型的数量必须是 1–100 的整数") + tc_diff = _norm_difficulty(item.get("difficulty")) + type_diffs.append(tc_diff) + types.append(TypeCount( + type=QuestionType(item["type"]), count=count, + difficulty=Difficulty(tc_diff) if tc_diff else None, + )) + + global_diff = _norm_difficulty(state.get("difficulty")) or next( + (d for d in type_diffs if d), None, + ) params = GenerateParams( kb_id=bank_id, doc_id=document_id, types=types, - difficulty=Difficulty(_norm_difficulty(state.get("difficulty"))), + difficulty=Difficulty(global_diff or "中"), source_mode=state.get("source_mode", "variant_data"), ) return params, str(state["scope"]).strip() diff --git a/backend/app/services/spaces.py b/backend/app/services/spaces.py index 27d8f47..27e8ffb 100644 --- a/backend/app/services/spaces.py +++ b/backend/app/services/spaces.py @@ -11,10 +11,13 @@ from app.services.auth import assert_version +CODE_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + def generate_space_code(db: Session) -> str: - """生成不可枚举的 96 位加入码,编号同时作为邀请凭据。""" + """生成 10 位随机编号(SP 前缀 + 8 位随机字符),编号同时作为邀请凭据。""" while True: - code = "SP" + secrets.token_hex(12).upper() + code = "SP" + "".join(secrets.choice(CODE_ALPHABET) for _ in range(8)) if not db.query(StudySpace.id).filter(StudySpace.code == code).first(): return code diff --git a/backend/tests/test_account_resource_regressions.py b/backend/tests/test_account_resource_regressions.py index c8719e4..23870fd 100644 --- a/backend/tests/test_account_resource_regressions.py +++ b/backend/tests/test_account_resource_regressions.py @@ -27,7 +27,7 @@ def test_transfer_keeps_previous_creator_edit_access(client, teacher, db): def test_removed_student_cannot_rejoin_space(client, teacher, student): space = client.post("/api/spaces", headers=teacher, json={"name": "隔离班级", "capacity": 50}).json() - assert re.fullmatch(r"SP[0-9A-F]{24}", space["code"]) + assert re.fullmatch(r"SP[0-9A-Z]{8}", space["code"]) assert client.post("/api/spaces/join", headers=student, json={"code": space["code"]}).status_code == 200 student_id = client.get("/api/auth/me", headers=student).json()["user"]["id"] diff --git a/backend/tests/test_acid_migration.py b/backend/tests/test_acid_migration.py index a338315..fc7fd7a 100644 --- a/backend/tests/test_acid_migration.py +++ b/backend/tests/test_acid_migration.py @@ -14,14 +14,15 @@ def test_main_and_ops_revisions_form_one_unambiguous_history() -> None: - """主线与智能体历史汇合,平台配置合并迁移成为唯一 head。""" + """主线与智能体历史汇合,对话轮次迁移成为唯一 head。""" versions = Path(__file__).resolve().parents[1] / "alembic" with warnings.catch_warnings(): warnings.filterwarnings( "error", message=r"Revision .* is present more than once", category=UserWarning, ) scripts = ScriptDirectory(str(versions)) - assert scripts.get_heads() == ["p1c2d3e45678"] + assert scripts.get_heads() == ["q2d3e4f56789"] + assert scripts.get_revision("q2d3e4f56789").down_revision == "p1c2d3e45678" assert scripts.get_revision("p1c2d3e45678").down_revision == ( "o0b1c2d34567", "j5f6g7h8i900", ) @@ -78,7 +79,7 @@ def test_upgrade_from_acid_history_preserves_existing_state(self) -> None: self.assertEqual(db.execute("SELECT COUNT(*) FROM generation_runs").fetchone(), (0,)) self.assertEqual(db.execute("PRAGMA foreign_key_check").fetchall(), []) self.assertEqual(db.execute("SELECT version_num FROM alembic_version").fetchone(), - ("p1c2d3e45678",)) + ("q2d3e4f56789",)) def test_legacy_ops_revision_requires_reconciliation_before_upgrade(self) -> None: """旧 V2 同号数据库不会被新版本图自动识别,也不能覆盖旧台账。""" @@ -95,6 +96,7 @@ def test_legacy_ops_revision_requires_reconciliation_before_upgrade(self) -> Non "o0b1c2d34567_generation_cancellation.py", "j5f6g7h8i900_platform_llm_settings.py", "p1c2d3e45678_merge_agent_platform.py", + "q2d3e4f56789_chat_requests.py", ): (versions / filename).unlink() ops = versions / "n9a0b1c23456_add_ops_runs.py" @@ -156,7 +158,7 @@ def test_upgrade_from_generation_history_preserves_existing_run(self) -> None: self.assertEqual(db.execute("SELECT * FROM generation_runs").fetchall(), before) self.assertEqual(db.execute("PRAGMA foreign_key_check").fetchall(), []) self.assertEqual(db.execute("SELECT version_num FROM alembic_version").fetchone(), - ("p1c2d3e45678",)) + ("q2d3e4f56789",)) def test_upgrade_preserves_answers_and_backfills_snapshot(self) -> None: with closing(sqlite3.connect(self.database)) as db: @@ -205,4 +207,4 @@ def test_upgrade_preserves_answers_and_backfills_snapshot(self) -> None: with closing(sqlite3.connect(self.database)) as db: self.assertEqual(db.execute("SELECT * FROM attempt_answers").fetchall(), before) self.assertEqual(db.execute("SELECT version_num FROM alembic_version").fetchone(), - ("p1c2d3e45678",)) + ("q2d3e4f56789",)) diff --git a/backend/tests/test_agent_main_migration.py b/backend/tests/test_agent_main_migration.py index 34394ee..72d2aa6 100644 --- a/backend/tests/test_agent_main_migration.py +++ b/backend/tests/test_agent_main_migration.py @@ -31,7 +31,7 @@ def test_upgrade_from_each_branch_preserves_history(tmp_path, monkeypatch, previ "encrypted_key='synthetic-ciphertext-not-a-real-credential' WHERE id=1" )) command.upgrade(config, "head") - assert ScriptDirectory.from_config(config).get_heads() == ["p1c2d3e45678"] + assert ScriptDirectory.from_config(config).get_heads() == ["q2d3e4f56789"] tables = inspect(engine).get_table_names() assert {"platform_llm_settings", "generation_tasks", "ops_runs"} <= set(tables) assert {"request_id", "execution_finished_at"} <= { @@ -40,7 +40,7 @@ def test_upgrade_from_each_branch_preserves_history(tmp_path, monkeypatch, previ with engine.connect() as connection: assert connection.execute(text( "SELECT version_num FROM alembic_version" - )).scalars().all() == ["p1c2d3e45678"] + )).scalars().all() == ["q2d3e4f56789"] assert connection.execute(text("PRAGMA foreign_key_check")).all() == [] if previous != "base": assert connection.execute(text( diff --git a/backend/tests/test_chat_requests.py b/backend/tests/test_chat_requests.py new file mode 100644 index 0000000..51ffa1c --- /dev/null +++ b/backend/tests/test_chat_requests.py @@ -0,0 +1,162 @@ +"""真实 HTTP 路径验证对话轮次的取消、发布和恢复。""" + +from concurrent.futures import ThreadPoolExecutor +from threading import Event +from uuid import uuid4 + +from app.api import chat +from app.db import SessionLocal +from app.models import ChatMessage, ChatRequest +from app.services import generation +from test_generation_runs import post_chat +from test_generation_runs import resources as resources + + +def test_cancel_before_send_is_durable_and_scoped(client, teacher, student, resources, monkeypatch): + base = f"/api/chat/sessions/{resources['session_id']}" + request_id = str(uuid4()) + url = f"{base}/requests/{request_id}" + + def unexpected(*args, **kwargs): + raise AssertionError("tombstoned request entered model preflight") + + monkeypatch.setattr(chat, "_message_api_key", unexpected) + assert client.get(url, headers=teacher).status_code == 404 + assert client.post(f"{base}/cancel", params={"request_id": request_id}, + headers=student).status_code == 404 + expected = {"status": "canceled", "execution_finished": True, "batch_id": None, "result": None} + for _ in range(2): + canceled = client.post(f"{base}/cancel", params={"request_id": request_id}, headers=teacher) + assert canceled.status_code == 202 + assert canceled.json() == expected + assert client.get(url, headers=student).status_code == 404 + assert client.get(url, headers=teacher).json() == expected + late = post_chat(client, teacher, resources, request_id=request_id) + assert late.status_code == 200 + assert late.json()["reply"] == chat.chat_flow.PAUSED_REPLY + assert client.get(f"{base}/requests/invalid", headers=teacher).status_code == 422 + assert client.post(f"{base}/cancel", params={"request_id": "invalid"}, + headers=teacher).status_code == 422 + assert post_chat(client, teacher, resources, request_id="invalid").status_code == 422 + with SessionLocal() as db: + assert db.query(ChatMessage).count() == 0 + + +def test_cancel_waits_for_the_target_execution_to_exit(client, teacher, resources, monkeypatch): + base = f"/api/chat/sessions/{resources['session_id']}" + entered, release = Event(), Event() + target, other = str(uuid4()), str(uuid4()) + + def detect(*args, **kwargs): + entered.set() + assert release.wait(15) + return {"intent": "generate", "confidence": "high"} + + monkeypatch.setattr(chat, "detect_intent", detect) + with ThreadPoolExecutor(max_workers=1) as executor: + pending = executor.submit(post_chat, client, teacher, resources, request_id=target) + try: + assert entered.wait(15) + assert client.get(f"{base}/requests/{target}", headers=teacher).json() == { + "status": "running", "execution_finished": False, "batch_id": None, "result": None, + } + assert client.post(f"{base}/cancel", params={"request_id": other}, + headers=teacher).json()["execution_finished"] is True + assert client.get(f"{base}/requests/{target}", headers=teacher).json()["status"] == "running" + for _ in range(2): + assert client.post(f"{base}/cancel", params={"request_id": target}, + headers=teacher).json() == { + "status": "canceled", "execution_finished": False, + "batch_id": None, "result": None, + } + assert post_chat(client, teacher, resources, request_id=str(uuid4())).status_code == 409 + finally: + release.set() + assert pending.result(timeout=15).json()["reply"] == chat.chat_flow.PAUSED_REPLY + assert client.get(f"{base}/requests/{target}", headers=teacher).json() == { + "status": "canceled", "execution_finished": True, "batch_id": None, "result": None, + } + with SessionLocal() as db: + assert db.query(ChatMessage).count() == 0 + + +def test_published_batch_recovers_only_surviving_current_questions( + client, teacher, resources, monkeypatch, +): + base = f"/api/chat/sessions/{resources['session_id']}" + request_id = str(uuid4()) + committed, release = Event(), Event() + record_commit = chat.GenerationRun.committed + + def hold_after_commit(run): + record_commit(run) + committed.set() + assert release.wait(15) + + monkeypatch.setattr(chat.GenerationRun, "committed", hold_after_commit) + with ThreadPoolExecutor(max_workers=1) as executor: + pending = executor.submit(post_chat, client, teacher, resources, request_id=request_id) + try: + assert committed.wait(15) + cancel = client.post(f"{base}/cancel", params={"request_id": request_id}, headers=teacher) + assert cancel.status_code == 202 + published = cancel.json() + assert published["status"] == "done" + assert published["execution_finished"] is False + assert published["result"]["questions"] + finally: + release.set() + sent = pending.result(timeout=15) + assert sent.status_code == 200, sent.text + original = sent.json() + assert published["result"] == original + removed, survivor = original["questions"] + assert removed["id"] and survivor["id"] + + def unexpected(*args, **kwargs): + raise AssertionError("published request started a second execution") + + monkeypatch.setattr(chat, "detect_intent", unexpected) + cancel = client.post(f"{base}/cancel", params={"request_id": request_id}, headers=teacher) + assert cancel.status_code == 202 + assert cancel.json() == { + "status": "done", "execution_finished": True, + "batch_id": original["batch_id"], "result": original, + } + assert client.delete(f"/api/questions/{removed['id']}", headers=teacher).status_code == 204 + edited = client.put(f"/api/questions/{survivor['id']}", headers=teacher, + json={"stem": "Edited question stem"}) + assert edited.status_code == 200 + status = client.get(f"{base}/requests/{request_id}", headers=teacher).json() + updated, = status["result"]["questions"] + assert status["batch_id"] == original["batch_id"] + assert updated["id"] == survivor["id"] + assert updated["stem"] == "Edited question stem" + assert updated["doc_name"] == "synthetic.md" + assert post_chat(client, teacher, resources, request_id=request_id).json() == status["result"] + assert client.post("/api/questions/batch-delete", headers=teacher, + json={"question_ids": [survivor["id"]]}).status_code == 204 + canceled = client.post(f"{base}/cancel", params={"request_id": request_id}, headers=teacher) + assert canceled.json()["result"]["questions"] == [] + assert post_chat(client, teacher, resources, request_id=request_id).json()["questions"] == [] + with SessionLocal() as db: + assert db.query(ChatMessage).count() == 2 + + +def test_failed_request_and_restart_have_distinct_terminal_states( + client, teacher, resources, monkeypatch, +): + base = f"/api/chat/sessions/{resources['session_id']}" + failed, interrupted = str(uuid4()), str(uuid4()) + monkeypatch.setattr(chat, "get_effective_deepseek_key", lambda *args: None) + assert post_chat(client, teacher, resources, request_id=failed).status_code == 400 + with SessionLocal() as db: + chat._begin_run(db, resources["session_id"], resources["owner"], request_id=interrupted) + generation.recover_interrupted_generation() + for request_id, state in ((failed, "failed"), (interrupted, "interrupted")): + assert client.get(f"{base}/requests/{request_id}", headers=teacher).json() == { + "status": state, "execution_finished": True, "batch_id": None, "result": None, + } + assert client.delete(base, headers=teacher).status_code == 204 + with SessionLocal() as db: + assert db.query(ChatRequest).count() == 0 diff --git a/backend/tests/test_chat_requirements.py b/backend/tests/test_chat_requirements.py index 2d19cd7..38470d8 100644 --- a/backend/tests/test_chat_requirements.py +++ b/backend/tests/test_chat_requirements.py @@ -160,3 +160,78 @@ def test_source_mode_defaults_without_becoming_required(complete_state, mocked_s def test_followup_remains_callable_without_state(): assert "多少" in slots.build_followup(["count"]) + + +def test_multi_level_difficulty_phrase_becomes_mixed_without_followup(complete_state, mocked_services): + """用户一次给出多个难度档(含同义词)时按混合难度出题,不再追问难度。""" + extract, generate = mocked_services + extract.return_value = {**complete_state, + "difficulty": "简单,中等,高难", "mixed_difficulty": True} + result = _chat({}) + assert result["done"] is True + generate.assert_called_once() + assert generate.call_args.kwargs.get("mixed_difficulty") is True + assert generate.call_args.kwargs.get("difficulty_note") == "简单,中等,高难" + assert result["slot_state"]["difficulty"] == "中" + assert result["slot_state"]["mixed_difficulty"] is True + + +@pytest.mark.parametrize("phrase,expected", [ + ("简单", "低"), ("容易", "低"), ("基础", "低"), ("中等", "中"), ("常规", "中"), + ("偏难", "高"), ("高难", "高"), ("困难", "高"), ("地狱", "地狱"), ("难度偏低", "低"), +]) +def test_single_difficulty_synonyms_normalize(phrase, expected): + assert slots._norm_difficulty(phrase) == expected + + +def test_mixed_phrase_falls_back_to_first_level_without_mid(complete_state, mocked_services): + extract, generate = mocked_services + extract.return_value = {**complete_state, + "difficulty": "简单和高难", "mixed_difficulty": True} + assert _chat({})["done"] is True + assert generate.call_args.kwargs.get("difficulty_note") == "简单和高难" + assert generate.call_args.kwargs.get("mixed_difficulty") is True + + +def test_per_type_difficulty_satisfies_requirement_without_followup(complete_state, mocked_services): + """按题型分别说明难度时不追问难度;缺知识点仍追问 scope。""" + extract, generate = mocked_services + extract.return_value = { + "types": [ + {"type": "single", "count": 5, "difficulty": "低"}, + {"type": "blank", "count": 2, "difficulty": "高"}, + {"type": "compute", "count": 4, "difficulty": "中"}, + ], + "mixed_difficulty": True, + } + result = _chat({}) + _assert_followup(result, generate) + assert slots.missing_keys(result["slot_state"]) == ["scope"] + + +def test_build_params_carries_per_type_difficulty(complete_state): + complete_state.pop("difficulty") + complete_state["types"] = [ + {"type": "single", "count": 5, "difficulty": "低"}, + {"type": "blank", "count": 2, "difficulty": "高"}, + ] + params, _ = slots.build_params(complete_state, "bank-test", "doc-test") + assert params.types[0].difficulty == Difficulty.low + assert params.types[1].difficulty == Difficulty.high + assert params.difficulty == Difficulty.low + + +def test_build_params_global_difficulty_overrides_missing_type_level(complete_state): + """整体难度存在、题型未单独说明时,题型难度留空由整体档兜底。""" + complete_state["types"] = [{"type": "single", "count": 3, "difficulty": None}] + params, _ = slots.build_params(complete_state, "bank-test", "doc-test") + assert params.difficulty == Difficulty.mid + assert params.types[0].difficulty is None + + +def test_merge_slots_updates_type_difficulty_across_turns(): + state = slots.merge_slots({}, {"types": [{"type": "single", "count": 5}]}) + state = slots.merge_slots(state, {"types": [{"type": "single", "count": None, + "difficulty": "简单"}]}) + assert state["types"] == [{"type": "single", "count": 5, "difficulty": "低"}] + assert "difficulty" not in slots.missing_keys(state) diff --git a/backend/tests/test_llm_errors.py b/backend/tests/test_llm_errors.py index 41390ed..08956f9 100644 --- a/backend/tests/test_llm_errors.py +++ b/backend/tests/test_llm_errors.py @@ -21,10 +21,10 @@ PRIVATE_URL = "https://private.example.test/fake?secret=fake-private-marker" PRIVATE_ERROR = f"{PRIVATE_MARKER} Bearer {FAKE_KEY} {PRIVATE_URL}" GENERIC_ERROR = "模型调用失败,请稍后重试" -MISSING_KEY_ERROR = "DeepSeek API Key 未配置:请到设置 → 模型与服务中填写" +MISSING_KEY_ERROR = "DeepSeek API Key 未配置:请到个人中心 → API 配置中填写" INVALID_JSON_ERROR = "模型返回的 JSON 无法解析,请重试" -AUTH_ERROR = "DeepSeek API Key 无效,请到设置 → 模型与服务检查密钥" -BALANCE_ERROR = "DeepSeek 账户余额不足,请到设置 → 模型与服务更换密钥或充值后重试" +AUTH_ERROR = "DeepSeek API Key 无效,请到个人中心 → API 配置检查密钥" +BALANCE_ERROR = "DeepSeek 账户余额不足,请到个人中心 → API 配置更换密钥或充值后重试" RATE_ERROR = "模型接口请求过于频繁,请等一两分钟再试" TIMEOUT_ERROR = "模型响应超时,请稍后重试" FAILURES = [ diff --git a/backend/tests/test_model_settings.py b/backend/tests/test_model_settings.py index 3ef457f..5741b00 100644 --- a/backend/tests/test_model_settings.py +++ b/backend/tests/test_model_settings.py @@ -370,6 +370,60 @@ def test_test_deepseek_with_key(client, teacher): assert resp.json()["ok"] is True +def test_test_deepseek_prefers_provided_key(client, teacher, monkeypatch): + """body 提供输入值时连接测试优先使用该值,不落库。""" + captured: dict[str, str] = {} + + def fake_chat_text(messages, *, api_key, temperature, max_tokens): + captured["api_key"] = api_key + return "Pong" + + monkeypatch.setattr(llm, "chat_text", fake_chat_text) + client.put( + "/api/users/me/model-settings", + json={"deepseek_api_key": "sk-saved-key-0001"}, + headers=teacher, + ) + resp = client.post( + "/api/users/me/model-settings/test-deepseek", + headers=teacher, + json={"deepseek_api_key": "sk-input-key-0002"}, + ) + assert resp.status_code == 200 + assert captured["api_key"] == "sk-input-key-0002" + data = client.get("/api/users/me/model-settings", headers=teacher).json() + assert data["deepseek_key_masked"] == "sk-****0001" + + +def test_test_mineru_prefers_provided_token( + client, teacher, mineru_response: MineruResponseStub, monkeypatch: pytest.MonkeyPatch, +): + """body 提供输入值时连接测试优先使用该值,不落库。""" + mineru_response(httpx.Response(200, json={"code": 0, "data": {}})) + captured: dict[str, str] = {} + original_ping = mineru.ping_token + + def fake_ping(token): + captured["token"] = token + return original_ping(token) + + monkeypatch.setattr(mineru, "ping_token", fake_ping) + client.put( + "/api/users/me/model-settings", + json={"mineru_token": "sk-saved-mineru-0001"}, + headers=teacher, + ) + resp = client.post( + "/api/users/me/model-settings/test-mineru", + headers=teacher, + json={"mineru_token": FAKE_MINERU_TOKEN}, + ) + assert resp.status_code == 200 + assert captured["token"] == FAKE_MINERU_TOKEN + data = client.get("/api/users/me/model-settings", headers=teacher).json() + assert data["mineru_token_masked"] == "sk-****0001" + + @pytest.mark.parametrize("error_type", [RuntimeError, llm.LLMError]) def test_deepseek_rejects_untrusted_exception_messages( client: TestClient, teacher: dict[str, str], monkeypatch: pytest.MonkeyPatch, diff --git a/backend/tests/test_ops_runs_migration.py b/backend/tests/test_ops_runs_migration.py index e805788..5c359e2 100644 --- a/backend/tests/test_ops_runs_migration.py +++ b/backend/tests/test_ops_runs_migration.py @@ -72,7 +72,7 @@ def test_upgrade_preserves_all_existing_tables_rows_and_does_not_backfill(histor config, engine, _sessions = historical_database before = historical_rows(engine) directory = ScriptDirectory.from_config(config) - assert directory.get_current_head() == "p1c2d3e45678" + assert directory.get_current_head() == "q2d3e4f56789" assert directory.get_revision(HEAD).down_revision == PREVIOUS command.upgrade(config, HEAD) assert historical_rows(engine) == before diff --git a/docs/api.md b/docs/api.md index 11e1606..d3f774f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -14,7 +14,7 @@ 单 worker 启动恢复将未完成的持久任务及运行中的会话标为 `interrupted`,同一事务将对应仍为 `accepted`/`running` 的台账标为 `unknown`,错误码为 `EXECUTION_INTERRUPTED`;无持久任务或会话关联的历史台账不被扫描。 -对话支持快速出题、创新命题、知识答疑和数据管理四种模式;参数化异步出题支持 request_id 幂等受理、按任务取消及执行退出确认;取消中仍占用生成门禁,一键清空的完整语义见[快速出题取消与清空](implementation/快速出题取消与清空.md)。图片与数据操作确认的契约和边界见[四模式对话与主线整合](design/对话四模式与主线整合.md)。 +对话支持快速出题、创新命题、知识答疑和数据管理四种模式。对话消息携带 request_id 时可按轮次暂停与查询结果;参数化异步出题支持 request_id 幂等受理、按任务取消及执行退出确认;取消中仍占用生成门禁,一键清空的完整语义见[快速出题取消与清空](implementation/快速出题取消与清空.md)。图片与数据操作确认的契约和边界见[四模式对话与主线整合](design/对话四模式与主线整合.md)。 运维 V2 提供管理员只读概览、运行列表及基本详情,响应 `schema_version` 为 `v2`。查询仅投影正式 SQL 台账,支持受理时间、账号、入口、状态及会话/任务/批次筛选,列表使用 `limit`/`offset`;未知与空值保留,不返回正文或质量结论。`from`/`to` 只接受带时区的 ISO 8601 字符串;数字时间戳、无效日期及 UTC 范围溢出返回 `422 VALIDATION_ERROR`。SQLAlchemy Enum 结果解码失败返回 `503 OPS_DATA_UNAVAILABLE`,不回显内部值或 SQL。`error_code` 仅展示已确认的 RunErrorCode 安全分类;未知值显示 `UNKNOWN`,无错误保留 `null`,旧分类和自由文本不直接透传。正式模型、增量迁移和两类出题入口已在 V2 分支与查询层整合;部署须先核验并升级迁移,表缺失、契约不兼容或读取失败返回 `503 OPS_DATA_UNAVAILABLE`,不回退合成数据。前端 V2 适配及隔离页面联调已完成,合并后及部署仍需验收。完整字段、错误和交接边界见[运维查询 V2 接口与查询设计](design/运维查询V2接口与查询设计.md),职责见[三人分工](implementation/运维后台三人实施分工方案.md)。依赖监测、告警、质量统计、复杂清理、自监控和正文审计不属于当前接口范围。 @@ -111,6 +111,7 @@ | `POST` | `/api/chat/sessions/{session_id}/confirm` | Confirm Operation | | `POST` | `/api/chat/sessions/{session_id}/messages` | Send Message | | `GET` | `/api/chat/sessions/{session_id}/progress` | Read Generation Progress | +| `GET` | `/api/chat/sessions/{session_id}/requests/{request_id}` | Read Chat Request | ## export @@ -225,4 +226,4 @@ | `POST` | `/api/users/me/model-settings/test-mineru` | 测试 MinerU 连接与鉴权(不验证文件解析) | | `PUT` | `/api/users/me/user-no` | Change User No | -共 120 个 HTTP 操作。WebSocket 契约与启动配置见根目录 README。 +共 121 个 HTTP 操作。WebSocket 契约与启动配置见根目录 README。 diff --git "a/docs/design/\345\257\271\350\257\235\345\207\272\351\242\230\345\277\205\345\241\253\344\277\241\346\201\257\346\243\200\346\237\245.md" "b/docs/design/\345\257\271\350\257\235\345\207\272\351\242\230\345\277\205\345\241\253\344\277\241\346\201\257\346\243\200\346\237\245.md" index f149961..eee007b 100644 --- "a/docs/design/\345\257\271\350\257\235\345\207\272\351\242\230\345\277\205\345\241\253\344\277\241\346\201\257\346\243\200\346\237\245.md" +++ "b/docs/design/\345\257\271\350\257\235\345\207\272\351\242\230\345\277\205\345\241\253\344\277\241\346\201\257\346\243\200\346\237\245.md" @@ -1,24 +1,26 @@ # 对话出题必填信息检查 -状态:已实现(2026-10-30),2026-11-11 随四模式整合更新来源要求。 +状态:已实现(2026-10-30),2026-11-11 随四模式整合更新来源要求,2026-11-19 升级为模型模板化抽取、题型级难度与自然追问。 ## 目标与使用范围 -保留 `/api/chat` 的多轮信息抽取、累积与追问流程。教师明确题型、每种题型数量、出题范围和难度后,才启动快速出题。题量没有默认 5 道的行为;参数化 `/api/generate` 继续遵循其原有契约。当前知识点流水线不再要求选择题目来源,显式来源值仍兼容,未提供时使用 `variant_data`;四模式差异见[整合说明](对话四模式与主线整合.md)。 +保留 `/api/chat` 的多轮信息抽取、累积与追问流程。教师明确题型、每种题型数量与难度(整体或按题型)、出题范围后,才启动快速出题。题量没有默认 5 道的行为;参数化 `/api/generate` 继续遵循其原有契约,`TypeCountBody` 支持可选的题型级 `difficulty`(低|中|高|地狱)。当前知识点流水线不再要求选择题目来源,显式来源值仍兼容,未提供时使用 `variant_data`;四模式差异见[整合说明](对话四模式与主线整合.md)。 ## 核心流程 -1. 信息抽取只采用教师明确表达的要求,未提及的字段保持缺失;不得使用助手举例中的数字,也不得自行分配多题型的总题量。 -2. 将新信息合入已有要求。教师没有重新说明数量时,保留之前明确的数量;新增题型未给数量时保持缺失,不补默认值。 -3. 逐项检查题型、各题型数量、范围、来源和难度。缺少题型时一并询问题型与数量;题型已知时,只列出数量缺失的题型。空白范围也视为缺失。 -4. 信息不完整时返回追问、累计状态、空题目列表及 `done=false`,不调用题目生成服务。没有追问轮数上限。 -5. 全部信息齐备后构造生成参数;参数构造也拒绝不完整要求,避免绕过编排检查时回退默认数量。 +1. 信息抽取由模型按固定 JSON 模板填写:知识点范围、题型列表(题型、数量、该题型难度)、总题量、整体难度、混合难度标记、来源模式与图片说明。只填教师明确表达的内容,未提及一律 `null`,同义词先归一(简单→低等)。同一题型给出多个难度档(如难度分别是简单、中等、高难)时按混合难度处理,整体难度档保留原始描述供生成指令使用。 +2. 将新信息合入已有要求。教师没有重新说明数量或难度时,保留之前明确的值;新增题型未给数量时保持缺失,不补默认值。 +3. 逐项检查题型、各题型数量、范围和难度。难度已被整体难度或任一题型难度满足时不再追问;缺少题型时一并询问题型与数量;题型已知时,只列出数量缺失的题型。空白范围也视为缺失。 +4. 信息不完整时先由模型生成自然追问(只问缺失项、不重复已确认信息,失败或未配置模型密钥时回退固定模板),并返回追问、累计状态、空题目列表及 `done=false`,不调用题目生成服务。没有追问轮数上限。 +5. 全部信息齐备后构造生成参数:题型级难度写入 `TypeCount.difficulty`,整体难度缺省时取第一个题型难度,再缺省回退中档;参数构造也拒绝不完整要求,避免绕过编排检查时回退默认数量。 ## 数据契约与异常边界 -请求与响应字段不变。`slot_state.types` 仍为题型与数量的列表;尚未确认的 `count` 为 `null`。`slot_state` 沿用前端逐轮回传方式。 +请求与响应字段不变。`slot_state.types` 为题型、数量与题型级难度的列表;尚未确认的 `count` 与未说明的题型级 `difficulty` 为 `null`。`slot_state` 沿用前端逐轮回传方式。 -数量沿用 `TypeCount` 的约束,每种题型为 1–20 道。布尔值、非整数、非有限数字、零、负数和超过上限的数量不能作为有效数量;在没有有效历史数量时继续追问。已有有效数量不会被后续未提及数量的抽取结果清空。 +数量沿用 `TypeCount` 的约束,每种题型为 1–100 道。布尔值、非整数、非有限数字、零、负数和超过上限的数量不能作为有效数量;在没有有效历史数量时继续追问。已有有效数量不会被后续未提及数量的抽取结果清空。 + +生成与审核链路按题型难度执行:命题提示词、考点规划、题目标注与盲评目标档均优先使用题型级难度,未单独指定难度的题型回退整体难度档;混合难度分布只作用于没有题型级难度的题型。换模板重出与配额补齐携带对应题型的难度。 模型负责从教师自然语言中抽取信息,后端负责结构和完整性检查。历史会话中已经填入的 5 无法辨别是教师明确要求还是旧代码默认值;本次不追溯改写历史状态,需要重新确认的旧会话应重新开始。 @@ -27,7 +29,9 @@ - 只给题型但未给数量时持续追问,不出题。 - 多题型中仅一部分明确数量时,只追问尚缺数量的题型。 - 后续补齐数量后,保留先前已明确的数量,齐备后才调用生成。 -- 范围或难度缺失时,即使数量齐备也不生成。 +- 范围缺失、且整体难度与题型级难度均未给出时,不生成。 +- 按题型分别说明难度(如 5 道低难度选择题、2 道高难度填空题)时不追问难度,缺范围只追问范围。 +- 同一题型给出多个难度档时按混合难度出题,不追问难度。 - 非法数量不能启动生成,不能自动截断小数或默认补为 5。 - 回归测试使用假的抽取与生成服务,不连接真实模型或知识库。 diff --git "a/docs/design/\345\257\271\350\257\235\345\233\233\346\250\241\345\274\217\344\270\216\344\270\273\347\272\277\346\225\264\345\220\210.md" "b/docs/design/\345\257\271\350\257\235\345\233\233\346\250\241\345\274\217\344\270\216\344\270\273\347\272\277\346\225\264\345\220\210.md" index 709c048..148931a 100644 --- "a/docs/design/\345\257\271\350\257\235\345\233\233\346\250\241\345\274\217\344\270\216\344\270\273\347\272\277\346\225\264\345\220\210.md" +++ "b/docs/design/\345\257\271\350\257\235\345\233\233\346\250\241\345\274\217\344\270\216\344\270\273\347\272\277\346\225\264\345\220\210.md" @@ -63,10 +63,16 @@ | POST | `/api/chat/sessions/{session_id}/confirm` | `confirm_id` 与布尔值 `accepted` | 消息请求在 `message`、`existing_stems` 之外包含 `images`、`mode`、`switch_only`。 -响应继续包含 `reply`、`questions`、`done`、`slot_state` 和 `batch_id`,并返回 +消息也可带客户端生成的 UUID `request_id`,用于精确暂停和恢复本轮结果。响应继续包含 `reply`、`questions`、`done`、`slot_state` 和 `batch_id`,并返回 `kind`、`mode`、`mode_changed`、`suggested_template`、`confirm`。 `kind` 的正常、模式不匹配及待澄清结果分别为 `reply`、`mode_mismatch`、`mode_confirm`。 +带 `request_id` 的 `POST /api/chat/sessions/{session_id}/cancel` 只暂停指定轮次。 +`GET /api/chat/sessions/{session_id}/requests/{request_id}` 查询同一轮次。 +状态响应包含 `status`、`execution_finished`、`batch_id` 和可恢复的 `result`。 +SQL 同事务裁决暂停和发布。暂停先提交时,旧轮次不能保存结果。发布先提交时,返回这一轮实际保存的结果。 +暂停先于消息抵达时记录取消,迟到消息结束且不启动模型。用户重复暂停时复用该轮状态。 + 数据操作预览的 `confirm` 包含确认 ID、操作及实体、影响数量和少量样本。确认有效期为 300 秒。预览和实际执行必须对应同一组目标,执行时再次校验归属,不能因重新扩大查询 而修改预览之外的记录。取消、过期和重复确认不得执行写操作。 diff --git "a/docs/design/\346\250\241\345\236\213\347\233\264\346\216\245\351\205\215\347\275\256\345\212\237\350\203\275\350\247\204\346\240\274.md" "b/docs/design/\346\250\241\345\236\213\347\233\264\346\216\245\351\205\215\347\275\256\345\212\237\350\203\275\350\247\204\346\240\274.md" index 1144fdc..e71f260 100644 --- "a/docs/design/\346\250\241\345\236\213\347\233\264\346\216\245\351\205\215\347\275\256\345\212\237\350\203\275\350\247\204\346\240\274.md" +++ "b/docs/design/\346\250\241\345\236\213\347\233\264\346\216\245\351\205\215\347\275\256\345\212\237\350\203\275\350\247\204\346\240\274.md" @@ -5,25 +5,24 @@ ## 目标与范围 -教师和学生仅在应用设置“模型与服务”维护自己的 DeepSeek API Key 与 MinerU Token,保存后用于对应业务。个人中心只保留个人资料与账号安全,不展示模型编辑或模型状态摘要。界面明确区分个人配置、系统默认与实际连通性,避免未保存表单被误认为已经生效。 +教师和学生仅在个人中心“API 配置”维护自己的 DeepSeek API Key 与 MinerU Token,保存后用于对应业务。个人中心同时提供资料头部与安全管理(修改密码、联系管理员)。界面明确区分个人配置、系统默认与实际连通性,避免未保存表单被误认为已经生效。 -普通设置只提供个人凭据编辑,`ModelSettings` 挂载 `settings/PersonalModelSettings.tsx`。DeepSeek 模型与地址由部署配置管理,嵌入与重排展示平台当前活动模型,普通用户不可编辑。当前不提供多提供方模型目录、配置命名、逐项默认选择、任务模型跟随/独立模式、模型列表发现或逐知识库嵌入绑定;旧目录编辑器及其孤立 API/类型已清理,不属于当前页面。 +个人凭据编辑由 `ProfileTab/ApiConfigCard.tsx` 提供:每行包含 Key 输入框与同行的测试、清空、保存按钮;默认展示服务端掩码(眼睛图标回显本机浏览器 localStorage 按用户隔离保存的完整 Key,其他电脑配置的 Key 只显示掩码并提示),点击输入框或清空按钮进入编辑态(可输入替换),失焦且未输入时保持空输入框不回填掩码;输入新值后保存替换,本机同步记录完整值。测试按钮无需先保存:输入值通过请求体传给测试接口即时验证,不落库;服务端契约见 `backend/app/schemas/auth.py` 的 `ModelTestBody`。DeepSeek 模型与地址由部署配置管理,嵌入与重排展示平台当前活动模型,普通用户不可编辑。当前不提供多提供方模型目录、配置命名、逐项默认选择、任务模型跟随/独立模式、模型列表发现或逐知识库嵌入绑定;旧目录编辑器及其孤立 API/类型已清理,不属于当前页面。 平台管理员在左侧导航、右侧内容的后台“模型与检索”维护系统嵌入/重排的模型标识、服务 URL 与凭据,Chroma 类型、路径和状态只读。嵌入模型/URL 保存为 pending,显式重建才应用;仅更新活动嵌入凭据或重排配置用于后续请求。详细流程、API、权限和运维边界以[设置拆分与保存反馈设计](设置拆分与保存反馈设计.md)为准。 ## 使用流程与交互 -1. 进入设置“模型与服务”后读取当前账号设置。加载中禁用修改;读取失败提供重新读取。 -2. DeepSeek 与 MinerU 各自展示个人配置状态及掩码,输入新凭据可替换。输入留空保留原值,清除必须显式勾选并保存。 -3. 保存当前两项发生变化的字段;未改字段不提交。保存失败保留输入;成功后读回正式状态。 -4. 写入成功但读回失败时明确提示“保存已完成”,清空可测试状态,允许重新读取。 -5. 只在没有未保存修改且设置读取成功时测试已保存配置。测试包含服务端默认兜底,不接收未保存凭据,不自动获取模型列表。 +1. 登录后读取当前账号设置;未配置 DeepSeek Key 时弹出引导弹窗并可跳转个人中心,智能出题发送被拦截。加载中禁用修改;读取失败提供重试。 +2. DeepSeek 与 MinerU 各自一行展示掩码(未配置时为空),输入新凭据可替换,输入留空不提交。 +3. 点击该行保存按钮仅提交该行输入的新凭据;保存失败保留输入;成功后读回正式掩码。 +4. 只在该行没有未保存输入时允许测试已保存配置。测试包含服务端默认兜底,不接收未保存凭据,不自动获取模型列表。 输入有 label,凭据使用 password 控件,加载、错误与成功状态分别展示。保存和模型测试使用顶部居中 toast,成功绿色约 3 秒、错误红色约 6 秒,带图标、文字、关闭按钮及辅助技术播报,字段错误在表单附近保留。 ## 配置与接口契约 -实现依据为 `backend/app/api/users.py`、`backend/app/schemas/auth.py`、`backend/app/services/model_settings.py` 和 `frontend/src/components/settings/PersonalModelSettings.tsx`。完整字段与调用流程见[配置来源与知识库流程](模型配置来源与普通知识库流程.md);管理员契约见 `backend/app/api/admin_rag.py` 与 `backend/app/schemas/rag_settings.py`,API 入口见[接口文档](../api.md)。 +实现依据为 `backend/app/api/users.py`、`backend/app/schemas/auth.py`、`backend/app/services/model_settings.py` 和 `frontend/src/components/tabs/ProfileTab/ApiConfigCard.tsx`。完整字段与调用流程见[配置来源与知识库流程](模型配置来源与普通知识库流程.md);管理员契约见 `backend/app/api/admin_rag.py` 与 `backend/app/schemas/rag_settings.py`,API 入口见[接口文档](../api.md)。 | 操作 | 当前接口与行为 | | --- | --- | @@ -56,7 +55,7 @@ DeepSeek 模型和地址由服务端配置,当前默认标识为 `deepseek-fla | 项目 | 当前状态与验收要求 | | --- | --- | -| 设置页个人配置与用户级接口 | 已实现;唯一编辑入口为设置“模型与服务”,个人中心仅资料与安全;核对会话变化后不保留他人结果 | +| 个人中心 API 配置与用户级接口 | 已实现;唯一编辑入口为个人中心“API 配置”,设置页已移除;核对会话变化后不保留他人结果 | | 保存、掩码、保留与显式清除 | 已实现;已有 `backend/tests/test_model_settings.py` 对默认、保存、掩码和清除的用例 | | 已保存配置连接测试 | 已实现;核对缺 Key、成功与 MinerU 失败、未保存输入或写后读回失败时禁用测试;与管理员草稿测试区分 | | 平台系统配置与普通用户边界 | 已实现;管理员可维护嵌入/重排模型、URL、凭据,普通用户只读活动模型;Chroma 信息只读,凭据不回显,空凭据保留,revision 冲突拒绝覆盖 | diff --git "a/docs/design/\346\250\241\345\236\213\351\205\215\347\275\256\346\235\245\346\272\220\344\270\216\346\231\256\351\200\232\347\237\245\350\257\206\345\272\223\346\265\201\347\250\213.md" "b/docs/design/\346\250\241\345\236\213\351\205\215\347\275\256\346\235\245\346\272\220\344\270\216\346\231\256\351\200\232\347\237\245\350\257\206\345\272\223\346\265\201\347\250\213.md" index 7bfa1ba..56d3c30 100644 --- "a/docs/design/\346\250\241\345\236\213\351\205\215\347\275\256\346\235\245\346\272\220\344\270\216\346\231\256\351\200\232\347\237\245\350\257\206\345\272\223\346\265\201\347\250\213.md" +++ "b/docs/design/\346\250\241\345\236\213\351\205\215\347\275\256\346\235\245\346\272\220\344\270\216\346\231\256\351\200\232\347\237\245\350\257\206\345\272\223\346\265\201\347\250\213.md" @@ -38,12 +38,12 @@ ## 个人配置流程与数据契约 -应用设置只保留“模型与服务”,由 [PersonalModelSettings.tsx](../../frontend/src/components/settings/PersonalModelSettings.tsx) 经 `frontend/src/api/modelSettings.ts` 转到统一会话请求层。个人中心只保留个人资料与安全,不再提供模型编辑或模型状态摘要;题库配置使用题库管理入口。 +个人模型凭据编辑入口为个人中心“API 配置”卡,由 [ApiConfigCard.tsx](../../frontend/src/components/tabs/ProfileTab/ApiConfigCard.tsx) 经 `frontend/src/api/backend.ts` 转到统一会话请求层。个人中心同时提供资料头部(昵称、账号 ID、身份)与安全管理(修改密码、联系管理员);题库配置使用题库管理入口。2026-11-18 起原“设置 → 模型与服务”页已移除,DeepSeek 与 MinerU Key 在该卡按行输入,保存后仅显示掩码,每行提供独立的测试与保存按钮。 -1. 登录后读取 `GET /api/users/me/model-settings`,展示当前模型、个人凭据掩码、MinerU 限制与平台活动嵌入/重排模型;后两项个人不可编辑。 -2. 输入新凭据并保存。输入框留空表示保留;清除须勾选对应选项后保存。前端拒绝仅空格输入。 -3. `PUT /api/users/me/model-settings` 成功返回 `{"saved": true}`,随后重新读取配置。写成功但读回失败时提示已保存、状态待重新读取,并禁用测试。 -4. 无未保存修改且读回成功时,点击测试已保存配置。测试不接收当前输入或任意提供方表单,不是模型列表发现。 +1. 登录后读取 `GET /api/users/me/model-settings`;未配置 DeepSeek Key 时登录后弹出引导弹窗,可跳转个人中心,智能出题发送被拦截。 +2. 在对应行输入新凭据并保存。未输入新值时输入框只读展示服务端掩码;输入后保存即替换。前端拒绝仅空格输入,界面不提供清除入口。 +3. `PUT /api/users/me/model-settings` 成功返回 `{"saved": true}`,随后重新读取配置刷新掩码;保存与测试按钮位于输入框同一行右侧。 +4. 无未保存输入且读回成功时,可点击该行测试按钮测试已保存配置。测试不接收当前输入或任意提供方表单,不是模型列表发现。 | 接口 | 请求/响应重点 | | --- | --- | diff --git "a/docs/design/\347\224\250\346\210\267\347\263\273\347\273\237\345\212\237\350\203\275\350\247\204\346\240\274.md" "b/docs/design/\347\224\250\346\210\267\347\263\273\347\273\237\345\212\237\350\203\275\350\247\204\346\240\274.md" index 9a02c2e..5104709 100644 --- "a/docs/design/\347\224\250\346\210\267\347\263\273\347\273\237\345\212\237\350\203\275\350\247\204\346\240\274.md" +++ "b/docs/design/\347\224\250\346\210\267\347\263\273\347\273\237\345\212\237\350\203\275\350\247\204\346\240\274.md" @@ -35,9 +35,9 @@ GET `/api/auth/config` 的 `AuthConfig` 增加必填 boolean `turnstile_enabled` | 会话与退出 | HS256 JWT 默认 15 分钟,SQL 持久化认证版本和设备会话,刷新绝对到期默认 7 天并逐次轮换。普通退出以本标签签名 Bearer 的 sid 撤销,仅清除同 sid 刷新 Cookie;注销单独允许过期 access,其他请求不允许 | | 浏览器与 Cookie | access 仅在内存;mc_refresh 为 HttpOnly、生产 Secure、SameSite=Lax、Path=/api/auth。refresh/logout 要求可信 Origin、JSON 与双提交 CSRF。安全操作只清目标用户 Cookie;跨标签锁串行 Cookie 写入,身份约束防止恢复为另一个账号 | | 普通资料 | PUT /api/users/me 只接收显示名、性别、手机、学校;不接收邮箱、学工号、角色或密码。gender/phone 省略保留、null 清空;显示名不能空,school 空串清空而 null 保留。保存等待服务端确认,失败保留草稿 | -| 模型设置 | 仅设置页“模型与服务”挂载 PersonalModelSettings,个人中心保留资料与安全;按用户保存 DeepSeek Key、MinerU Token,GET 只返回配置状态与掩码。省略或 null 保留,空串清除;界面空输入保留、显式勾选清除。测试仅使用已保存的有效配置,可能包含服务端默认值;未保存修改时禁用测试。系统嵌入与重排配置归管理员,见[设置拆分设计](设置拆分与保存反馈设计.md) | +| 模型设置 | 仅个人中心“API 配置”卡(`ProfileTab/ApiConfigCard.tsx`)编辑,设置页已移除;按用户保存 DeepSeek Key、MinerU Token,GET 只返回配置状态与掩码。省略或 null 保留,空串清除;界面点击输入框或清空按钮进入编辑,失焦空草稿保持空框不回填,掩码经眼睛回显本机保存值。测试无需先保存:输入值经 `ModelTestBody` 传入即时验证,不落库;该行未配置且无输入时禁用测试。两项 Key 均未配置时登录弹引导弹窗且智能出题禁止发送。系统嵌入与重排配置归管理员,见[设置拆分设计](设置拆分与保存反馈设计.md) | | 题库及个人记录 | 仅教师可创建题库;创建者按 account 添加启用教师/学生,creator/editor/readonly 三档,编号自助加入关闭。历史学生创建资源保留归属和访问;转让只给启用教师。共享题库不公开他人的题目、收藏、聊天或试卷 | -| 空间 | 当前为 SP 加 96 位随机加入码,旧顺序码通过迁移轮换;被移除成员不能凭码恢复,不能沿用旧文档“空间加入完全不变”的约束 | +| 空间 | 当前为 SP 加 8 位随机字符、共 10 位的随机加入码(2026-11-18 起,旧 26 位码与顺序码不再新发);被移除成员不能凭码恢复,不能沿用旧文档“空间加入完全不变”的约束 | | 开发账号与测试 | seed 仅 development+显式开关创建教师/学生,dev_ 标记供发布审计;生产不初始化这类开发账号。测试用临时 SQLite、逐测试独立 fakeredis 与假外部服务,屏蔽个人配置和真实网络,不再清空 Redis 15 | ## 当前限制与验收边界 diff --git "a/docs/design/\347\237\245\350\257\206\345\272\223\346\250\241\345\235\227\350\257\264\346\230\216.md" "b/docs/design/\347\237\245\350\257\206\345\272\223\346\250\241\345\235\227\350\257\264\346\230\216.md" index 1b46831..d45f7a7 100644 --- "a/docs/design/\347\237\245\350\257\206\345\272\223\346\250\241\345\235\227\350\257\264\346\230\216.md" +++ "b/docs/design/\347\237\245\350\257\206\345\272\223\346\250\241\345\235\227\350\257\264\346\230\216.md" @@ -81,7 +81,7 @@ OpenAPI 多个成功响应仍为未细化的 `schema: {}`,部分业务错误 ## 4. 模型配置来源:各阶段分别解析 -个人配置存于 `UserModelSetting`,入口为应用设置“模型与服务”和 `GET/PUT /api/users/me/model-settings`,不是历史 `/api/settings`。个人中心只保留资料与安全;普通设置已移除旧知识库连接、引擎与解析分区,题库配置从题库管理进入。平台配置由管理员左侧导航/右侧内容后台的“模型与检索”维护。 +个人配置存于 `UserModelSetting`,入口为个人中心“API 配置”卡和 `GET/PUT /api/users/me/model-settings`,不是历史 `/api/settings`。原“设置 → 模型与服务”页已于 2026-11-18 移除;个人中心提供资料头部、安全管理与 API 配置;题库配置从题库管理进入。平台配置由管理员左侧导航/右侧内容后台的“模型与检索”维护。 跨模型与资料入库的完整配置优先级见 [模型配置来源与普通知识库流程](模型配置来源与普通知识库流程.md),个人页面的保存、清除、读回与测试规则见 [模型配置功能规格](模型直接配置功能规格.md)。 diff --git "a/docs/design/\347\256\241\347\220\206\345\221\230\344\270\216\350\264\246\345\217\267\345\274\200\351\200\232\350\256\276\350\256\241.md" "b/docs/design/\347\256\241\347\220\206\345\221\230\344\270\216\350\264\246\345\217\267\345\274\200\351\200\232\350\256\276\350\256\241.md" index a39843d..f7fd3ee 100644 --- "a/docs/design/\347\256\241\347\220\206\345\221\230\344\270\216\350\264\246\345\217\267\345\274\200\351\200\232\350\256\276\350\256\241.md" +++ "b/docs/design/\347\256\241\347\220\206\345\221\230\344\270\216\350\264\246\345\217\267\345\274\200\351\200\232\350\256\276\350\256\241.md" @@ -30,7 +30,7 @@ | 管理员权限 | 管理面板不额外授予用户题库正文、对话、作答或个人模型凭据访问权限;教学资源权限解析拒绝 admin,管理员需要教学功能时使用独立教学账号 | | 题库创建与成员 | 仅教师可创建,学生前端隐藏入口、直接 POST 也拒绝;creator/editor/readonly 三档,创建者按 account 添加启用教师/学生。编号加入关闭;历史学生创建库保留归属与访问,转让仅给启用教师,原创建者降为 editor | | 个人记录与文件 | 题目、收藏、聊天、组卷按账号归属;成员共享不公开他人个人记录。文档按题库和文档 ID 存储,授权不靠个人磁盘目录;历史聊天重新校验题库成员资格 | -| 学习空间 | 教师创建管理,学生凭随机 SP+96 位加入码加入;旧顺序码迁移轮换,removed 成员不能凭码重新加入。题库成员权限不自动获得空间资源 | +| 学习空间 | 教师创建管理,学生凭随机加入码(SP+8 位随机字符,共 10 位,2026-11-18 起)加入;旧顺序码迁移轮换,removed 成员不能凭码重新加入。题库成员权限不自动获得空间资源 | | 迁移与隔离测试 | 沿用既有认证、随机空间码及改密提醒迁移,本轮不新增模型或迁移,保留 account、密码、用户 ID 和外键;邮箱缺失/未验证审计仅为信息项。测试用临时 SQLite、独立 fakeredis、假外部服务,不清空本机 Redis | ## 当前核心流程与接口 diff --git "a/docs/design/\350\256\276\347\275\256\346\213\206\345\210\206\344\270\216\344\277\235\345\255\230\345\217\215\351\246\210\350\256\276\350\256\241.md" "b/docs/design/\350\256\276\347\275\256\346\213\206\345\210\206\344\270\216\344\277\235\345\255\230\345\217\215\351\246\210\350\256\276\350\256\241.md" index e77ebfa..806beb0 100644 --- "a/docs/design/\350\256\276\347\275\256\346\213\206\345\210\206\344\270\216\344\277\235\345\255\230\345\217\215\351\246\210\350\256\276\350\256\241.md" +++ "b/docs/design/\350\256\276\347\275\256\346\213\206\345\210\206\344\270\216\344\277\235\345\255\230\345\217\215\351\246\210\350\256\276\350\256\241.md" @@ -1,6 +1,7 @@ # 设置拆分与保存反馈设计 > 状态:已实现;实际 SQL 迁移、Chroma 原路径与运行设置服务已核验,完整后端全量基线已通过,末轮定向验证与独立审查已完成。日期:2026-11-10。 +> 2026-11-18 起个人模型配置入口迁移至个人中心“API 配置”卡,原“设置 → 模型与服务”页已移除,本文关于设置页的职责描述为迁移前记录;保存反馈与拆分原则继续有效。 > 用户已确认完整方案;本文依据当前前后端实现同步。文末原有测试数字属于历史批次,本次最终结果见文末增量记录。原 PDF 仍 failed、chunks=0,没有将存储恢复等同于资料入库或真实模型/OCR 验收。 ## 目标与使用范围 diff --git "a/docs/implementation/\345\277\253\351\200\237\345\207\272\351\242\230\345\217\226\346\266\210\344\270\216\346\270\205\347\251\272.md" "b/docs/implementation/\345\277\253\351\200\237\345\207\272\351\242\230\345\217\226\346\266\210\344\270\216\346\270\205\347\251\272.md" index b92a77f..3060671 100644 --- "a/docs/implementation/\345\277\253\351\200\237\345\207\272\351\242\230\345\217\226\346\266\210\344\270\216\346\270\205\347\251\272.md" +++ "b/docs/implementation/\345\277\253\351\200\237\345\207\272\351\242\230\345\217\226\346\266\210\344\270\216\346\270\205\347\251\272.md" @@ -2,7 +2,7 @@ ## 目标与范围 -解决 #11、#13:清空当前题目时取消参数化异步任务,阻止迟到结果发布,等待该执行及所属模型线程退出后再允许重新生成。复用 SQL 持久任务、运行台账和按 token 释放的 Redis 租约。同步出题和对话取消沿用原接口。 +解决 #11、#13:清空当前题目时取消参数化异步任务,阻止迟到结果发布,等待该执行及所属模型线程退出后再允许重新生成。复用 SQL 持久任务、运行台账和按 token 释放的 Redis 租约。同步出题沿用原接口。对话暂停通过现有取消端点的轮次参数和轮次查询完成确认。 ## 生命周期与契约 @@ -24,6 +24,13 @@ 增量迁移新增请求标识和执行结束时间,历史终态回填结束时间;单 worker 启动把遗留 queued/running/canceling 执行收束为 interrupted,不重新调用模型。存在新字段业务数据时拒绝有损降级。 +## 对话暂停与预览清空 + +点击暂停直接发送取消请求。发送按钮显示灰色加载圆圈。服务端确认指定轮次已经停止且执行器退出前,发送、重试和清空均保持禁用。 +取消响应可以通过原请求标识找回。断连后可手动重试,刷新后继续确认同一轮。 +暂停前已经提交的轮次会恢复回复和仍存活的题目,并在预览恢复后开放清空。 +一键清空只删除确认时预览里的题目,保留对话和历史消息。参数化任务仍由独立的恢复清理入口处理。 + ## 验收 使用临时 SQLite、进程内 FakeRedis、假模型和事件屏障验证:排队取消、运行取消与等待退出、重复取消、取消和提交两种顺序、旧 run/锁隔离、启动幂等及响应丢失、越权、重启恢复,以及前端迟到回调、失败重试与刷新恢复。接口契约与生成 API 文档同批更新。 diff --git a/frontend/README.md b/frontend/README.md index ac53bb8..214c9c4 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -90,12 +90,12 @@ Ubuntu + Node 22 的 CI 在仓库根目录执行以下完整命令: ```bash cd frontend npm ci -npx playwright-core install --with-deps chromium +npx --no-install playwright-core install chromium npm run lint npm test ``` -Windows 本地安装浏览器使用 `npx playwright-core install chromium`,其余命令相同。首次安装 npm 依赖与 Chromium 需要网络;安装完成后回归使用内存 API 和假 Turnstile,无需后端、Redis、真实账号、模型或个人环境文件。 +CI 使用 Ubuntu 24.04 runner 预装的 Chromium 系统库。精简 Linux 环境可用 `npx --no-install playwright-core install --with-deps chromium` 补装系统依赖。Windows 本地安装使用上面的命令。首次安装 npm 依赖与 Chromium 需要网络;安装完成后回归使用内存 API 和假 Turnstile,无需后端、Redis、真实账号、模型或个人环境文件。 `npm test` 与 `npm run test:regression` 都会先执行 TypeScript 检查和一次生产构建,再按以下固定顺序逐个运行脚本: @@ -130,7 +130,7 @@ CI 无需额外执行 `npm run typecheck` 或 `npm run build`。若同一 job ## 功能要点 -- 个人凭据在“模型与服务”保存:留空保留,明确勾选后清除;连接测试使用已保存配置。管理员在“模型与检索”维护平台模型与索引重建,嵌入模型变更需重建后生效。 +- 个人凭据在“个人中心 → API 配置”保存:留空保留,保存后仅显示掩码,眼睛图标可回显本机浏览器保存的完整 Key(在其他电脑配置的 Key 只显示掩码);连接测试使用已保存配置,未配置 DeepSeek Key 时智能出题禁止发送。管理员在“模型与检索”维护平台模型与索引重建,嵌入模型变更需重建后生效。 - 题库支持 PDF、DOCX、XLSX、MD/markdown、TXT 批量上传;校验格式、空文件及名称/大小/修改时间重复项,部分失败可只重试未受理文件。上传受理后仍需等待后台处理完成,列表可查看失败详情。 - MD/TXT 提供分页文本预览,文本读取上限为 2 MiB;PDF 通过认证请求获取 Blob 后打开窗口,DOCX/XLSX 提供下载。关闭或切换文档时取消预览请求。 - 当前出题界面采用 agent 布局:右侧保留可折叠历史侧栏,选择题库与文档、打开或删除历史会话;“新建对话”保留历史记录,快速面板和快捷提问已移除。保留创新命题、知识答疑、数据管理、图片和操作确认。历史加载期间禁止发送、重试及编辑,Context 入口也同步校验;详情接口必传当前 `mode`,续聊与重试沿用服务端模式,避免误切到快速出题并重置已有上下文。恢复有消息的会话时收起模式控制器,空会话仍显示并选中服务端模式。会话删除等待服务端成功后移出列表,失败保留列表与确认框。消息编辑或回退重发、模式切换与数据操作沿用忙碌保护。 diff --git a/frontend/e2e-auth.mjs b/frontend/e2e-auth.mjs index 15cd94c..4c045ad 100644 --- a/frontend/e2e-auth.mjs +++ b/frontend/e2e-auth.mjs @@ -123,7 +123,7 @@ await context.route('**/*', async route => { else if (path === '/api/admin/overview') body = { accounts: { admin_active: 1 }, resources: {}, task_status_counts: {}, tasks: [], task_total: 0, recent_task_limit: 50, admin_contact: '测试管理员' } else if (path === '/api/admin/accounts') body = [] else if (path.startsWith('/api/admin/ops/')) { status = 503; body = { detail: { code: 'NOT_INTEGRATED', message: '合成运维服务未接入' } } } - else if (path.includes('model-settings')) body = { mineru_limits: {}, embedding_model: 'test', rerank_model: 'test' } + else if (path.includes('model-settings')) body = { deepseek_key_configured: true, mineru_token_configured: true, mineru_limits: {}, embedding_model: 'test', rerank_model: 'test' } else if (path === '/api/generate/batches/latest') body = null else if (path === '/api/chat/sessions') { authenticated(); assert.equal(method, 'GET'); body = { items: [] } } else if (path === '/api/urges' || path === '/api/notifications') body = { unread_count: 0, items: [] } diff --git a/frontend/merge-frontend-regression.mjs b/frontend/merge-frontend-regression.mjs index b7035b2..463f10d 100644 --- a/frontend/merge-frontend-regression.mjs +++ b/frontend/merge-frontend-regression.mjs @@ -1,4 +1,4 @@ -/* global URL, console, process, window, Event, File, Response, AbortSignal */ +/* global URL, console, process, window, File, Response, AbortSignal */ /** 主线整合风险回归:真实 React/题库适配层,内存假服务,浏览器所有网络均阻断。 */ import assert from 'node:assert/strict' import { runChatHistoryCases, runGenerationTaskCases } from './merge-session-cases.mjs' @@ -38,7 +38,7 @@ const bundle = await build({ import {ApiError} from './src/api/backend'; import {ToastProvider} from './src/store/ToastContext'; import Toast from './src/components/ui/Toast'; - import {SettingsPage} from './src/components/settings/SettingsPage'; + import {ApiConfigCard} from './src/components/tabs/ProfileTab/ApiConfigCard'; import BankCreateModal from './src/components/tabs/BankTab/BankCreateModal'; import BankEditModal from './src/components/tabs/BankTab/BankEditModal'; import BankViewModal from './src/components/tabs/BankTab/BankViewModal'; @@ -77,11 +77,7 @@ const bundle = await build({ {h.mode === 'history' && } - {h.mode === 'settings' && <> - - - {app.activeTab === 'settings' && } - } + {h.mode === 'settings' && } {h.mode === 'create' && } {h.mode === 'edit' && } {h.mode === 'view' && } @@ -165,10 +161,11 @@ async function mount(mode, role = 'teacher', memberRole = 'creator', format = 'T listChatSessions: () => h.sessions ?? [], getChatSession: id => ({session_id:id, mode:'generate', messages:[]}), listQuestions: () => ({items:[]}), listBanks: () => h.banks ?? [h.apiBank], latestBatch: () => ({batch_id:null, questions:[]}), - getModelSettings: () => ({deepseek_model:'fake-deepseek', deepseek_key_configured:false, - deepseek_key_masked:null, mineru_token_configured:false, mineru_token_masked:null, + getModelSettings: () => ({deepseek_model:'fake-deepseek', deepseek_key_configured:true, + deepseek_key_masked:'sk-****kOJl', mineru_token_configured:false, mineru_token_masked:null, mineru_limits:{max_file_mb:100, max_pages:200}, embedding_model:'fake-embedding', rerank_model:'fake-rerank'}), saveModelSettings: () => {}, + testDeepSeek: () => {}, testMinerU: () => {}, listFavoriteGroups: () => [], listFavorites: () => h.favoriteRows, listPapers: () => h.paperRows, listSpaces: () => [], getPaperApi: id => h.paperRows.find(paper => paper.id === id), mapPaper: paper => paper, @@ -191,7 +188,8 @@ async function mount(mode, role = 'teacher', memberRole = 'creator', format = 'T sendChatMessage: (...args) => h.chatReply({mode:args[5]}), confirmChat: () => ({reply:'操作已确认', done:true}), deleteChatSession: () => {}, batchDeleteQuestions: () => {}, - getChatProgress: () => ({active:true, percent:20, stage:'合成进度'}), cancelChat: () => {}, + getChatProgress: () => ({active:true, percent:20, stage:'合成进度'}), + cancelChat: () => ({status:'canceled', execution_finished:true, batch_id:null, result:null}), startGeneration: () => ({task_id:'fake-task'}), findGenerationRequest: () => ({task_id:'fake-task'}), cancelGeneration: () => ({done:true, execution_finished:true, status:'canceled', progress:0, @@ -255,55 +253,64 @@ async function prepareConfirmation(page, entity, action = 'delete') { { if (!(process.argv.includes('--chat-only') || process.argv.includes('--generation-only'))) { const settings = await mount('settings') - await settings.getByRole('button', {name:'打开个人设置', exact:true}).click() - const key = settings.getByLabel('新的 DeepSeek API Key', {exact:true}) + const key = settings.getByLabel('请输入您的校内 DeepSeek Key', {exact:true}) + await settings.getByText('校内 DeepSeek Key', {exact:true}).waitFor() + // DeepSeek 已配置:browse 态展示服务端掩码;MinerU 未配置时测试与保存不可用 + assert.equal(await key.inputValue(), 'sk-****kOJl') + assert.equal(await settings.getByRole('button', {name:'测试', exact:true}).last().isDisabled(), true) + assert.equal(await settings.getByRole('button', {name:'保存', exact:true}).last().isDisabled(), true) + // 本机没有保存过完整 Key 时,眼睛提示需要重新输入 + await settings.getByRole('button', {name:'显示完整 Key', exact:true}).first().click() + await settings.getByText('完整 Key 仅保存在配置它的这台电脑上').first().waitFor() + // 测试当前输入的 Key 不落库 + await key.click() await key.fill('synthetic-draft-key') - await settings.waitForFunction(() => window.mergeApp.hasUnsavedChanges) - const leaveSettings = settings.getByRole('button', {name:'离开个人设置', exact:true}) - let dialog = settings.waitForEvent('dialog') - let click = leaveSettings.click() - await (await dialog).dismiss() - await click - assert.equal(await key.inputValue(), 'synthetic-draft-key') - assert.equal(await settings.evaluate(() => !window.dispatchEvent(new Event('beforeunload', {cancelable:true}))), true) - dialog = settings.waitForEvent('dialog') - click = leaveSettings.click() - await (await dialog).accept() - await click - await settings.waitForFunction(() => window.mergeApp.activeTab === 'preview' && !window.mergeApp.hasUnsavedChanges) - await settings.getByRole('button', {name:'打开个人设置', exact:true}).click() - await key.waitFor() - assert.equal(await key.inputValue(), '') - await key.fill('synthetic-saved-key') + const testButton = settings.getByRole('button', {name:'测试', exact:true}).first() + assert.equal(await testButton.isDisabled(), false) + await settings.evaluate(() => { window.mergeHarness.held.testDeepSeek = true }) + await testButton.click() + await settings.waitForFunction(() => window.mergeHarness.pending.testDeepSeek?.length === 1) + assert.equal(await settings.evaluate(() => window.mergeHarness.calls.some(call => call.name === 'saveModelSettings')), false) + await settings.evaluate(() => window.mergeHarness.finish('testDeepSeek')) + await settings.getByText('校内 DeepSeek 连接成功').first().waitFor() + // 保存携带草稿值并读回新掩码 await settings.evaluate(() => { window.mergeHarness.held.saveModelSettings = true }) - await settings.getByRole('button', {name:'保存配置', exact:true}).click() + await settings.getByRole('button', {name:'保存', exact:true}).first().click() await settings.waitForFunction(() => window.mergeHarness.pending.saveModelSettings?.length === 1) - await leaveSettings.click() - assert.equal(await settings.evaluate(() => window.mergeApp.activeTab), 'settings') - assert.equal(await settings.evaluate(() => window.mergeApp.isSettingsSaving), true) - await settings.getByRole('alert').filter({hasText:'配置正在保存,请等待完成后再离开'}).waitFor() + assert.deepEqual(await settings.evaluate(() => window.mergeHarness.pending.saveModelSettings[0].args[0]), + {deepseek_api_key:'synthetic-draft-key'}) await settings.evaluate(() => { - const h = window.mergeHarness; h.held.getModelSettings = true; h.finish('saveModelSettings'); + const h = window.mergeHarness + h.held.getModelSettings = true + h.finish('saveModelSettings') }) await settings.waitForFunction(() => window.mergeHarness.pending.getModelSettings?.length === 1) - await settings.waitForFunction(input => input.value === '', await key.elementHandle()) - assert.equal(await key.inputValue(), '') - assert.equal(await settings.evaluate(() => !window.dispatchEvent(new Event('beforeunload', {cancelable:true}))), true) - await leaveSettings.click() - assert.equal(await settings.evaluate(() => window.mergeApp.activeTab), 'settings') await settings.evaluate(() => { - const h = window.mergeHarness; h.held.getModelSettings = false; + const h = window.mergeHarness + h.held.getModelSettings = false h.finish('getModelSettings', {deepseek_model:'fake-deepseek', deepseek_key_configured:true, - deepseek_key_masked:'***', mineru_token_configured:false, mineru_token_masked:null, - mineru_limits:{max_file_mb:100, max_pages:200}, embedding_model:'fake-embedding', rerank_model:'fake-rerank'}); + deepseek_key_masked:'sk-****yZ8w', mineru_token_configured:false, mineru_token_masked:null, + mineru_limits:{max_file_mb:100, max_pages:200}, embedding_model:'fake-embedding', rerank_model:'fake-rerank'}) }) - await settings.getByRole('status').filter({hasText:'模型配置已保存。现在可以测试已保存的配置。'}).last().waitFor() - await settings.waitForFunction(() => !window.mergeApp.isSettingsSaving && !window.mergeApp.hasUnsavedChanges) - assert.equal(await settings.evaluate(() => !window.dispatchEvent(new Event('beforeunload', {cancelable:true}))), false) - await leaveSettings.click() - await settings.waitForFunction(() => window.mergeApp.activeTab === 'preview') + await settings.getByText('校内 DeepSeek Key 已保存').first().waitFor() + await settings.waitForFunction(() => + window.document.querySelector('input[aria-label="请输入您的校内 DeepSeek Key"]').value === 'sk-****yZ8w') + // 完整 Key 只写入本机浏览器,供眼睛图标回显 + assert.deepEqual(await settings.evaluate(() => JSON.parse(window.localStorage.getItem('mathcraft-personal-keys'))), + {A:{deepseek:'synthetic-draft-key'}}) + await settings.getByRole('button', {name:'显示完整 Key', exact:true}).first().click() + await settings.waitForFunction(() => + window.document.querySelector('input[aria-label="请输入您的校内 DeepSeek Key"]').value === 'synthetic-draft-key') + await settings.getByRole('button', {name:'显示掩码', exact:true}).first().click() + await settings.waitForFunction(() => + window.document.querySelector('input[aria-label="请输入您的校内 DeepSeek Key"]').value === 'sk-****yZ8w') + // 清空草稿后保持编辑态,不回填掩码 + await key.click() + await key.fill('new-draft') + await settings.getByRole('button', {name:'清空校内 DeepSeek Key输入', exact:true}).click() + assert.equal(await key.inputValue(), '') await settings.close() - pass('personal settings keep cancelled drafts, confirm discard, block navigation and refresh throughout save/readback, retain real Toast feedback') + pass('api config card tests unsaved key without persisting, saves and reads back masked value, eye reveals local full key, clear keeps edit mode') const student = await mount('create', 'student') assert.equal(await student.getByRole('heading', {name:'新建题库', exact:true}).count(), 0) @@ -1216,7 +1223,9 @@ async function prepareConfirmation(page, entity, action = 'delete') { await chat.waitForFunction(() => window.mergeApp.selectedDocId === 'doc-bank-A') await chat.evaluate(() => { window.mergeHarness.held.sendChatMessage = true; void window.mergeApp.sendChat('第一次') }) await chat.waitForFunction(() => window.mergeHarness.pending.sendChatMessage?.length === 1) - await chat.evaluate(() => { window.mergeApp.pauseChat(); void window.mergeApp.sendChat('第二次') }) + await chat.evaluate(() => window.mergeApp.pauseChat()) + await chat.waitForFunction(() => !window.mergeApp.botThinking) + await chat.evaluate(() => { void window.mergeApp.sendChat('第二次') }) await chat.waitForFunction(() => window.mergeHarness.pending.sendChatMessage.length === 2) await chat.evaluate(() => window.mergeHarness.finish('sendChatMessage', window.mergeHarness.chatReply({reply:'旧结果', mode:'data'}))) await chat.waitForFunction(() => window.mergeHarness.pending.sendChatMessage.length === 1) diff --git a/frontend/merge-session-cases.mjs b/frontend/merge-session-cases.mjs index 91aa8ea..ec7b2cc 100644 --- a/frontend/merge-session-cases.mjs +++ b/frontend/merge-session-cases.mjs @@ -172,6 +172,74 @@ export async function runChatHistoryCases({ providerCase, selectBank, settleRend assert.equal(await page.evaluate(() => window.mergeHarness.calls.some(c => c.name === 'batchDeleteQuestions')), false) }) + await providerCase('pause waits for server and restores a committed batch before clear', async page => { + await seed(page) + await page.evaluate(() => { + const h = window.mergeHarness + h.held.sendChatMessage = h.held.cancelChat = h.held.getChatTurn = true + void window.mergeApp.sendChat('等待生成结果') + }) + await page.waitForFunction(() => window.mergeHarness.pending.sendChatMessage?.length === 1) + await page.getByRole('button', {name:'暂停', exact:true}).click() + assert.equal(await page.getByRole('button', {name:'正在暂停', exact:true}).isDisabled(), true) + assert.equal(await page.getByRole('button', {name:'正在暂停', exact:true}).locator('svg').count(), 1) + await page.evaluate(() => window.mergeApp.setActiveTab('preview')) + assert.equal(await page.getByRole('button', {name:'一键清空', exact:true}).isDisabled(), true) + await page.evaluate(() => { + const h = window.mergeHarness + h.finish('cancelChat', {status:'done', execution_finished:false, batch_id:'late', result:null}) + }) + await page.waitForFunction(() => window.mergeHarness.pending.getChatTurn?.length === 1) + assert.equal(await page.getByRole('button', {name:'一键清空', exact:true}).isDisabled(), true) + await page.evaluate(() => { + const h = window.mergeHarness + h.finish('getChatTurn', {status:'done', execution_finished:true, batch_id:'late', + result:h.chatReply({reply:'已完成该轮', batch_id:'late', questions:[{id:'late-question'}]})}) + }) + await page.waitForFunction(() => !window.mergeApp.botThinking + && window.mergeApp.questions.some(question => question.id === 'late-question')) + await page.getByRole('button', {name:'一键清空', exact:true}).click() + await page.getByRole('button', {name:'确认清空', exact:true}).click() + await page.waitForFunction(() => window.mergeApp.questions.length === 0) + assert.equal(await page.evaluate(() => window.mergeApp.messages.some(m => m.text === '已完成该轮')), true) + assert.equal(await page.evaluate(() => window.mergeHarness.calls + .some(call => call.name === 'batchDeleteQuestions' && call.args[0].includes('late-question'))), true) + }) + + await providerCase('failed pause stays locked and refresh continues the original request', async page => { + await seed(page) + await page.evaluate(() => { + const h = window.mergeHarness + h.held.sendChatMessage = h.held.cancelChat = true + void window.mergeApp.sendChat('等待暂停确认') + }) + await page.waitForFunction(() => window.mergeHarness.pending.sendChatMessage?.length === 1) + await page.getByRole('button', {name:'暂停', exact:true}).click() + await page.waitForFunction(() => window.mergeHarness.pending.cancelChat?.length === 1) + await page.evaluate(() => window.mergeHarness.pending.cancelChat.shift().reject(new Error('断连'))) + await page.getByRole('button', {name:'重试暂停', exact:true}).waitFor() + await page.evaluate(() => window.mergeApp.setActiveTab('preview')) + assert.equal(await page.getByRole('button', {name:'一键清空', exact:true}).isDisabled(), true) + await page.evaluate(() => { + const h = window.mergeHarness + h.backend.latestBatch = () => ({batch_id:'preview-batch', questions:[{id:'preview-result'}]}) + h.generation += 1 + window.remountMerge() + }) + await page.waitForFunction(() => window.mergeHarness.pending.cancelChat?.length === 1) + const requestIds = await page.evaluate(() => ({ + sent: window.mergeHarness.calls.filter(call => call.name === 'sendChatMessage').at(-1).args[7], + paused: window.mergeHarness.calls.filter(call => call.name === 'cancelChat').map(call => call.args[1]), + })) + assert.deepEqual(requestIds.paused, [requestIds.sent, requestIds.sent]) + await page.evaluate(() => window.mergeHarness.finish('cancelChat', { + status:'canceled', execution_finished:true, batch_id:null, result:null, + })) + await page.waitForFunction(() => !window.mergeApp.botThinking && window.mergeApp.chatPauseStatus === null) + assert.equal(await page.evaluate(() => window.mergeApp.questions[0]?.id), 'preview-result') + assert.equal(await page.evaluate(() => window.mergeApp.docs.some(doc => doc.id === 'doc-bank-A')), true) + }) + await providerCase('preview clear batches at 200; partial failure keeps all local questions and favorites until retry succeeds', async page => { await page.evaluate(() => { const h = window.mergeHarness diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 25f777d..dbbe6a5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -12,7 +12,7 @@ import RecordsTab from './components/tabs/RecordsTab' import FavoritesTab from './components/tabs/FavoritesTab' import SpaceTab from './components/tabs/SpaceTab' import ProfileTab from './components/tabs/ProfileTab' -import { SettingsPage } from './components/settings/SettingsPage' +import ApiConfigModal from './components/tabs/ProfileTab/ApiConfigModal' import Toast from './components/ui/Toast' import LoginPage from './components/auth/LoginPage' import AdminPanel from './components/admin/AdminPanel' @@ -25,11 +25,7 @@ function Shell() {
- {activeTab === 'settings' ? ( -
- -
- ) : activeTab === 'bank' ? ( + {activeTab === 'bank' ? (
@@ -58,6 +54,7 @@ function Shell() {
{activeTab === 'generate' && }
+ ) } diff --git a/frontend/src/api/backend.ts b/frontend/src/api/backend.ts index bc4002a..ef2cdf4 100644 --- a/frontend/src/api/backend.ts +++ b/frontend/src/api/backend.ts @@ -290,8 +290,8 @@ export function mapDocument(doc: ApiDocument): KbDocument & { api: ApiDocument } status: doc.status, stage: doc.stage, progress: doc.progress, api: doc } } -export async function listDocuments(bankId: string): Promise { - return request(`/api/banks/${bankId}/documents`) +export async function listDocuments(bankId: string, signal?: AbortSignal): Promise { + return request(`/api/banks/${bankId}/documents`, { signal }) } export async function getDocument(bankId: string, docId: string): Promise { @@ -479,11 +479,12 @@ export async function cancelGeneration(taskId: string): Promise { const params = new URLSearchParams() if (bankId) params.set('bank_id', bankId) if (documentId) params.set('document_id', documentId) - return request(`/api/generate/batches/latest?${params.toString()}`) + return request(`/api/generate/batches/latest?${params.toString()}`, { signal }) } export async function listQuestions(params: { @@ -492,12 +493,12 @@ export async function listQuestions(params: { document_id?: string page?: number page_size?: number -}): Promise<{ items: ApiQuestion[]; total: number }> { +}, signal?: AbortSignal): Promise<{ items: ApiQuestion[]; total: number }> { const search = new URLSearchParams() Object.entries(params).forEach(([k, v]) => { if (v !== undefined && v !== '') search.set(k, String(v)) }) - return request(`/api/questions?${search.toString()}`) + return request(`/api/questions?${search.toString()}`, { signal }) } export async function updateQuestionApi(q: Question): Promise { @@ -986,15 +987,12 @@ export async function reviewAttempt(attemptId: string): Promise & { school?: string }): Promise { - return request('/api/users/me', { - method: 'PUT', - body: JSON.stringify({ - display_name: patch.name, - gender: patch.gender === '' ? null : patch.gender, - phone: patch.phone === '' ? null : patch.phone, - school: patch.school, - }), - }) + const body: Record = {} + if (patch.name !== undefined) body.display_name = patch.name + if (patch.gender !== undefined) body.gender = patch.gender === '' ? null : patch.gender + if (patch.phone !== undefined) body.phone = patch.phone === '' ? null : patch.phone + if (patch.school !== undefined) body.school = patch.school + return request('/api/users/me', { method: 'PUT', body: JSON.stringify(body) }) } export interface ModelSettings { @@ -1026,12 +1024,18 @@ export async function saveModelSettings(payload: { }) } -export async function testDeepSeek(): Promise { - await request('/api/users/me/model-settings/test-deepseek', { method: 'POST' }) +export async function testDeepSeek(key?: string): Promise { + await request('/api/users/me/model-settings/test-deepseek', { + method: 'POST', + body: JSON.stringify(key ? { deepseek_api_key: key } : {}), + }) } -export async function testMinerU(): Promise { - await request('/api/users/me/model-settings/test-mineru', { method: 'POST' }) +export async function testMinerU(token?: string): Promise { + await request('/api/users/me/model-settings/test-mineru', { + method: 'POST', + body: JSON.stringify(token ? { mineru_token: token } : {}), + }) } /* ---------------- 对话出题 ---------------- */ @@ -1072,8 +1076,8 @@ export interface BackendChatDetail { messages: ApiChatMessage[] } -export async function getChatSession(sessionId: string): Promise { - return request(`/api/chat/sessions/${sessionId}`) +export async function getChatSession(sessionId: string, signal?: AbortSignal): Promise { + return request(`/api/chat/sessions/${sessionId}`, { signal }) } export async function createChatSession(bankId: string, documentId: string, signal?: AbortSignal): Promise { @@ -1084,6 +1088,15 @@ export async function createChatSession(bankId: string, documentId: string, sign }) } +export type ChatMessageResult = Omit & { questions: ApiQuestion[] } + +export interface ChatTurnStatus { + status: 'running' | 'canceled' | 'done' | 'failed' | 'interrupted' + execution_finished: boolean + batch_id: string | null + result: ChatMessageResult | null +} + export async function sendChatMessage( sessionId: string, message: string, @@ -1092,7 +1105,8 @@ export async function sendChatMessage( images: string[] = [], mode: ChatMode = 'generate', switchOnly = false, -): Promise & { questions: ApiQuestion[] }> { + requestId?: string, +): Promise { return request(`/api/chat/sessions/${sessionId}/messages`, { method: 'POST', body: JSON.stringify({ @@ -1100,6 +1114,7 @@ export async function sendChatMessage( existing_stems: existingStems, mode, switch_only: switchOnly, + request_id: requestId, ...(images.length ? { images } : {}), }), signal, @@ -1126,8 +1141,14 @@ export async function getChatProgress( return request(`/api/chat/sessions/${sessionId}/progress`, { signal }) } -export async function cancelChat(sessionId: string): Promise { - await request<{ canceled: boolean }>(`/api/chat/sessions/${sessionId}/cancel`, { method: 'POST' }) +export async function cancelChat(sessionId: string, requestId: string, signal: AbortSignal): Promise { + return request(`/api/chat/sessions/${sessionId}/cancel?request_id=${encodeURIComponent(requestId)}`, { + method: 'POST', signal, + }) +} + +export async function getChatTurn(sessionId: string, requestId: string, signal: AbortSignal): Promise { + return request(`/api/chat/sessions/${sessionId}/requests/${encodeURIComponent(requestId)}`, { signal }) } export async function deleteChatSession(sessionId: string): Promise { diff --git a/frontend/src/api/modelSettings.ts b/frontend/src/api/modelSettings.ts deleted file mode 100644 index 61333f0..0000000 --- a/frontend/src/api/modelSettings.ts +++ /dev/null @@ -1,3 +0,0 @@ -/** 个人模型设置统一复用带会话校验的当前用户 API。 */ -export { getModelSettings, saveModelSettings, testDeepSeek, testMinerU } from './backend' -export type { ModelSettings } from './backend' diff --git a/frontend/src/components/layout/SideNav.tsx b/frontend/src/components/layout/SideNav.tsx index f74b75f..8ebfe2a 100644 --- a/frontend/src/components/layout/SideNav.tsx +++ b/frontend/src/components/layout/SideNav.tsx @@ -1,12 +1,12 @@ import type { LucideIcon } from 'lucide-react' -import { BookOpen, Database, FileText, Home, PanelLeftClose, PanelLeftOpen, Settings, Star, User } from 'lucide-react' +import { BookOpen, Database, FileText, Home, PanelLeftClose, PanelLeftOpen, Star, User } from 'lucide-react' import { useApp } from '../../store/AppContext' const NAV_ITEMS: { key: string label: string icon: LucideIcon - tab?: 'generate' | 'bank' | 'records' | 'fav' | 'space' | 'me' | 'settings' + tab?: 'generate' | 'bank' | 'records' | 'fav' | 'space' | 'me' }[] = [ { key: 'home', label: '智能出题', icon: Home, tab: 'generate' }, { key: 'space', label: '学习空间', icon: BookOpen, tab: 'space' }, @@ -14,7 +14,6 @@ const NAV_ITEMS: { { key: 'paper', label: '组卷记录', icon: FileText, tab: 'records' }, { key: 'bank', label: '题库管理', icon: Database, tab: 'bank' }, { key: 'me', label: '个人中心', icon: User, tab: 'me' }, - { key: 'settings', label: '设置', icon: Settings, tab: 'settings' }, ] export default function SideNav() { diff --git a/frontend/src/components/layout/TabBar.tsx b/frontend/src/components/layout/TabBar.tsx index 5e026e5..05962bf 100644 --- a/frontend/src/components/layout/TabBar.tsx +++ b/frontend/src/components/layout/TabBar.tsx @@ -12,11 +12,11 @@ const TABS: { key: TabKey; label: string; icon: LucideIcon }[] = [ export default function TabBar() { const { - activeTab, setActiveTab, startNewChat, clearQuestions, botThinking, sessionLoading, + activeTab, setActiveTab, startNewChat, clearQuestions, botThinking, chatPauseStatus, sessionLoading, confirmBusy, pendingConfirm, generating, generationClearing, questionsClearing, generationRecoveryError, resetGenerationRecovery, retryGenerationCleanup, } = useApp() - const clearDisabled = botThinking || sessionLoading || confirmBusy || pendingConfirm !== null + const clearDisabled = botThinking || chatPauseStatus != null || sessionLoading || confirmBusy || pendingConfirm !== null || generating || generationClearing || questionsClearing || generationRecoveryError !== null const [confirmClear, setConfirmClear] = useState(false) const [confirmReset, setConfirmReset] = useState(false) diff --git a/frontend/src/components/settings/ModelSettings.tsx b/frontend/src/components/settings/ModelSettings.tsx deleted file mode 100644 index 05d66b0..0000000 --- a/frontend/src/components/settings/ModelSettings.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { PersonalModelSettings } from './PersonalModelSettings' - -interface ModelSettingsProps { - onDirtyChange?: (dirty: boolean) => void - onSavingChange?: (saving: boolean) => void -} - -export function ModelSettings({ onDirtyChange, onSavingChange }: ModelSettingsProps) { - return -} diff --git a/frontend/src/components/settings/PersonalModelSettings.tsx b/frontend/src/components/settings/PersonalModelSettings.tsx deleted file mode 100644 index ddc06fe..0000000 --- a/frontend/src/components/settings/PersonalModelSettings.tsx +++ /dev/null @@ -1,195 +0,0 @@ -import { Loader2 } from 'lucide-react' -import { useCallback, useEffect, useId, useRef, useState } from 'react' -import { getModelSettings, saveModelSettings, testDeepSeek, testMinerU } from '../../api/modelSettings' -import type { ModelSettings } from '../../api/modelSettings' -import { useToast } from '../../store/ToastContext' - -interface PersonalModelSettingsProps { - onDirtyChange?: (dirty: boolean) => void - onSavingChange?: (saving: boolean) => void -} - -/** 设置页个人凭据编辑;测试只验证服务端已保存的配置。 */ -export function PersonalModelSettings({ onDirtyChange, onSavingChange }: PersonalModelSettingsProps) { - const { showToast } = useToast() - const [model, setModel] = useState(null) - const [deepseekKey, setDeepseekKey] = useState('') - const [mineruToken, setMineruToken] = useState('') - const [clearDeepseek, setClearDeepseek] = useState(false) - const [clearMineru, setClearMineru] = useState(false) - const [busy, setBusy] = useState<'load' | 'save' | 'deepseek' | 'mineru' | null>('load') - const [error, setError] = useState('') - const [notice, setNotice] = useState('') - const lock = useRef(false) - const mounted = useRef(false) - const id = useId() - const dirty = deepseekKey !== '' || mineruToken !== '' || clearDeepseek || clearMineru - const disabled = busy !== null || model === null - - useEffect(() => { onDirtyChange?.(dirty) }, [dirty, onDirtyChange]) - useEffect(() => () => onDirtyChange?.(false), [onDirtyChange]) - useEffect(() => () => onSavingChange?.(false), [onSavingChange]) - useEffect(() => { - if (!dirty && busy !== 'save') return - const preventLoss = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' } - window.addEventListener('beforeunload', preventLoss) - return () => window.removeEventListener('beforeunload', preventLoss) - }, [dirty, busy]) - - const reportError = useCallback((message: string) => { - if (!mounted.current) return - setError(message) - showToast(message, 'error') - }, [showToast]) - - const reportSuccess = (message: string) => { - if (!mounted.current) return - setNotice(message) - showToast(message, 'success') - } - - const load = useCallback(async () => { - if (lock.current) return - lock.current = true - setBusy('load') - setError('') - try { - const fresh = await getModelSettings() - if (mounted.current) setModel(fresh) - } catch { - reportError('模型配置读取失败,请重试。') - } finally { - lock.current = false - if (mounted.current) setBusy(null) - } - }, [reportError]) - - useEffect(() => { - mounted.current = true - void load() - return () => { mounted.current = false } - }, [load]) - - const save = async () => { - if (lock.current || !model || !dirty) return - if ((!clearDeepseek && deepseekKey !== '' && !deepseekKey.trim()) || - (!clearMineru && mineruToken !== '' && !mineruToken.trim())) { - reportError('凭据不能仅含空格;如需删除,请勾选清除个人凭据。') - return - } - lock.current = true - setBusy('save') - onSavingChange?.(true) - setError('') - setNotice('') - try { - await saveModelSettings({ - ...(clearDeepseek ? { deepseek_api_key: '' } : deepseekKey.trim() ? { deepseek_api_key: deepseekKey.trim() } : {}), - ...(clearMineru ? { mineru_token: '' } : mineruToken.trim() ? { mineru_token: mineruToken.trim() } : {}), - }) - if (!mounted.current) return - setDeepseekKey('') - setMineruToken('') - setClearDeepseek(false) - setClearMineru(false) - // 写入已确认后,读回失败需明确提示,不能以旧状态继续测试。 - setModel(null) - try { - const fresh = await getModelSettings() - if (!mounted.current) return - setModel(fresh) - reportSuccess('模型配置已保存。现在可以测试已保存的配置。') - } catch { - reportError('保存已完成,但最新配置读取失败。请重新读取后再测试。') - } - } catch { - reportError('模型配置保存未获确认,请重试;当前输入已保留。') - } finally { - lock.current = false - onSavingChange?.(false) - if (mounted.current) setBusy(null) - } - } - - const test = async (service: 'deepseek' | 'mineru') => { - if (lock.current || !model) return - if (dirty) { - reportError('请先保存当前修改,再测试已保存的配置。') - return - } - lock.current = true - setBusy(service) - setError('') - setNotice('') - try { - if (service === 'deepseek') await testDeepSeek() - else await testMinerU() - reportSuccess(service === 'mineru' - ? 'MinerU 已保存配置鉴权通过,实际解析仍受额度和任务结果影响(含服务端默认配置)。' - : 'DeepSeek 已保存配置连接测试通过(含服务端默认配置)。') - } catch { - reportError('已保存配置测试失败,请检查凭据或服务可用性。') - } finally { - lock.current = false - if (mounted.current) setBusy(null) - } - } - - const inputClass = 'block w-full rounded-lg border border-line bg-white px-3 py-2 text-sm text-ink outline-none focus:border-primary disabled:opacity-60' - const buttonClass = 'rounded-lg border border-line px-3 py-2 text-sm text-ink-2 hover:border-primary disabled:opacity-50' - const edit = (change: () => void) => { change(); setNotice(''); setError('') } - - return
-
-

个人模型配置

- -
-

留空表示保留原凭据;勾选清除后点击保存。测试只使用已保存的配置,请先保存修改。

- {busy === 'load' &&

正在读取配置…

} - {error &&

{error}

} - {notice &&

{notice}

} - {!model && busy === null && } -
-
- {model?.deepseek_model ?? 'DeepSeek'} -

{model ? model.deepseek_key_configured ? `已配置个人 Key ${model.deepseek_key_masked ?? ''}` : '未配置个人 Key' : '配置尚未读取'}

- - edit(() => setDeepseekKey(event.target.value))} className={inputClass} /> - -

清除后服务端可能使用系统默认 Key;没有默认 Key 时服务不可用。

- -
-
- MinerU OCR -

{model ? model.mineru_token_configured ? `已配置个人 Token ${model.mineru_token_masked ?? ''}` : '未配置个人 Token;如服务端已配置默认 Token 则使用,否则不可用。' : '配置尚未读取'}

- - edit(() => setMineruToken(event.target.value))} className={inputClass} /> - -

清除后仅在服务端已配置默认 Token 时使用;没有默认 Token 时 OCR 不可用。

- {model &&

单文件 ≤ {model.mineru_limits.max_file_mb} MB,页数 ≤ {model.mineru_limits.max_pages} 页

} -

测试仅验证已保存配置的连接和鉴权,不保证任务解析成功、额度充足或内容可用。

- -
- {dirty &&

有未保存的修改,请先保存再测试。

} - {model &&
-

系统向量模型(由管理员配置):{model.embedding_model}

-

系统重排模型(由管理员配置):{model.rerank_model}

-
} -
-
-} diff --git a/frontend/src/components/settings/SettingsPage.tsx b/frontend/src/components/settings/SettingsPage.tsx deleted file mode 100644 index f5383d0..0000000 --- a/frontend/src/components/settings/SettingsPage.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { useApp } from '../../store/AppContext' -import { ModelSettings } from './ModelSettings' - -export function SettingsPage() { - const { setHasUnsavedChanges, setIsSettingsSaving } = useApp() - return
-
-

模型与服务

-

管理个人 DeepSeek 与 MinerU 服务配置。题库配置请前往题库管理。

-
-
- -
-
-} diff --git a/frontend/src/components/tabs/GenerateTab/ChatInput.tsx b/frontend/src/components/tabs/GenerateTab/ChatInput.tsx index 14e304b..fd14153 100644 --- a/frontend/src/components/tabs/GenerateTab/ChatInput.tsx +++ b/frontend/src/components/tabs/GenerateTab/ChatInput.tsx @@ -1,4 +1,4 @@ -import { CheckCircle2, ShieldAlert, SendHorizontal, Square, X, XCircle } from 'lucide-react' +import { CheckCircle2, LoaderCircle, ShieldAlert, SendHorizontal, Square, X, XCircle } from 'lucide-react' import { useApp } from '../../../store/AppContext' import { CHAT_MODE_LABELS } from '../../../types' import SegmentedControl from '../../ui/SegmentedControl' @@ -65,15 +65,22 @@ function ConfirmOverlay() { export default function ChatInput() { const { inputDraft, setInputDraft, sendChat, botThinking, showToast, - selectedDocId, pauseChat, chatImages, removeChatImage, + selectedDocId, pauseChat, chatPauseStatus, chatImages, removeChatImage, mode, setMode, sessionMode, modeVisible, messages, confirmBusy, pendingConfirm, sessionLoading, questionsClearing, generating, generationRecoveryError, + modelSettings, } = useApp() - const interactionBusy = botThinking || sessionLoading || questionsClearing || generating + // 未配置 DeepSeek API Key 时禁止发送;配置读取中不拦截 + const deepseekReady = modelSettings ? modelSettings.deepseek_key_configured : true + const interactionBusy = botThinking || chatPauseStatus != null || sessionLoading || questionsClearing || generating || generationRecoveryError !== null || confirmBusy || pendingConfirm !== null - const canSend = (inputDraft.trim().length > 0 || chatImages.length > 0) && !interactionBusy + const canSend = (inputDraft.trim().length > 0 || chatImages.length > 0) && !interactionBusy && deepseekReady const submit = () => { + if (!deepseekReady) { + showToast('请先在「个人中心 → API 配置」保存 DeepSeek API Key,再发送出题请求') + return + } if (!canSend) return if (!selectedDocId) { showToast('请先在右侧选择知识库文档,才能基于知识库出题') @@ -139,9 +146,32 @@ export default function ChatInput() { className="block w-full resize-none bg-transparent px-1 text-sm leading-6 text-ink outline-none placeholder:text-ink-3" />
+ {chatPauseStatus === 'failed' && ( +
+ 暂停未确认 + +
+ )} + {!deepseekReady && ( + 未配置 DeepSeek API Key,无法发送;请前往「个人中心 → API 配置」保存 + )}
{inputDraft.length}/2000 - {botThinking ? ( + {chatPauseStatus != null ? ( + + ) : botThinking ? ( - - + {i === lastUserIndex && ( + + )}
)} {m.role === 'assistant' && ( diff --git a/frontend/src/components/tabs/ProfileTab/ApiConfigCard.tsx b/frontend/src/components/tabs/ProfileTab/ApiConfigCard.tsx new file mode 100644 index 0000000..49f588f --- /dev/null +++ b/frontend/src/components/tabs/ProfileTab/ApiConfigCard.tsx @@ -0,0 +1,275 @@ +/** 个人中心 API 配置卡:DeepSeek 与 OCR-MinerU Key 的保存与连接测试。 + * Key 保存到服务端账户(供后端调用),同时完整值保存在本机浏览器(localStorage,按用户隔离), + * 供眼睛图标在本机回显;服务端接口只返回掩码,不回传完整凭据。 */ +import { Eraser, HelpCircle, Info, Loader2, Save } from 'lucide-react' +import { Eye, EyeOff } from 'lucide-react' +import { useRef, useState } from 'react' +import { saveModelSettings, testDeepSeek, testMinerU } from '../../../api/backend' +import { useAuth } from '../../../store/AuthContext' +import { useApp } from '../../../store/AppContext' + +type Service = 'deepseek' | 'mineru' +type Busy = `${Service}-save` | `${Service}-test` | null + +const KEY_STORE = 'mathcraft-personal-keys' + +function readStoredKey(userId: string, service: Service): string { + try { + const raw = localStorage.getItem(KEY_STORE) + if (!raw) return '' + const store = JSON.parse(raw) as Record>> + return store[userId]?.[service] ?? '' + } catch { + return '' + } +} + +function writeStoredKey(userId: string, service: Service, value: string) { + try { + const raw = localStorage.getItem(KEY_STORE) + const store = raw ? JSON.parse(raw) as Record>> : {} + localStorage.setItem(KEY_STORE, JSON.stringify({ + ...store, + [userId]: { ...store[userId], [service]: value }, + })) + } catch { + /* 存储被禁用时跳过本机回显,不影响保存 */ + } +} + +interface ApiKeyRowProps { + label: string + placeholder: string + hint: string + service: Service + configured: boolean + masked: string | null + saving: boolean + testing: boolean + onSave: (value: string) => Promise + onTest: (value?: string) => Promise +} + +function ApiKeyRow({ label, placeholder, hint, service, configured, masked, saving, testing, onSave, onTest }: ApiKeyRowProps) { + const { user } = useAuth() + const { showToast } = useApp() + const userId = user?.userId ?? '' + const inputRef = useRef(null) + // 本机保存的完整 Key;在其他设备配置的 Key 只能显示服务端掩码 + const [fullKey, setFullKey] = useState(() => readStoredKey(userId, service)) + const [draft, setDraft] = useState('') + // browse:展示掩码/完整 Key;edit:填写草稿。仅保存成功回到 browse,清空后保持 edit 避免回填 + const [mode, setMode] = useState<'browse' | 'edit'>('browse') + const [reveal, setReveal] = useState(false) + const busy = saving || testing + const trimmed = draft.trim() + const dirty = trimmed !== '' + // browse:明文展示打码掩码(sk-****abcd),眼睛切换为本机完整 Key;edit:显示草稿 + const display = dirty + ? draft + : mode === 'edit' ? '' : reveal && fullKey ? fullKey : configured ? masked ?? '' : '' + + const save = () => { + if (busy || !dirty) return + void onSave(trimmed).then(() => { + writeStoredKey(userId, service, trimmed) + setFullKey(trimmed) + setDraft('') + setMode('browse') + setReveal(false) + }) + } + + const clear = () => { + if (busy) return + setDraft('') + setMode('edit') + setReveal(false) + inputRef.current?.focus() + } + + const toggleReveal = () => { + if (dirty) { setReveal((v) => !v); return } + if (!fullKey) { + showToast('完整 Key 仅保存在配置它的这台电脑上;本机没有记录,请重新输入 Key 并保存一次', 'error') + return + } + if (mode === 'edit') { + // 编辑态草稿为空时点眼睛 = 填入本机保存的完整 Key,便于查看或覆盖 + setDraft(fullKey) + setReveal(true) + return + } + setReveal((v) => !v) + } + + const showEye = mode === 'edit' || configured + const eyeTitle = dirty + ? (reveal ? '隐藏输入内容' : '显示输入内容') + : mode === 'edit' && fullKey + ? '填入本机保存的完整 Key' + : reveal ? '显示掩码' : '显示完整 Key' + + return ( +
+
+ +
+ { + // 浏览态点击输入框即进入编辑并清空草稿,避免掩码展示值混入输入被误保存 + if (mode === 'browse' && !dirty) { + setMode('edit') + setDraft('') + setReveal(false) + } + }} + onChange={(e) => setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && !e.nativeEvent.isComposing) save() + }} + className="block w-full rounded-lg border border-line bg-white py-2 pl-3 pr-9 text-sm text-ink outline-none transition-colors placeholder:text-ink-3 focus:border-primary disabled:opacity-60" + disabled={busy} + /> + {showEye && ( + + )} +
+ + + +
+

{hint}

+
+ ) +} + +/** API 配置卡:输入框缩短,右侧同行放置测试与保存按钮 */ +export function ApiConfigCard() { + const { modelSettings, refreshModelSettings, showToast } = useApp() + const [busy, setBusy] = useState(null) + + const save = async (service: Service, value: string) => { + if (busy) return + setBusy(`${service}-save`) + try { + await saveModelSettings(service === 'deepseek' ? { deepseek_api_key: value } : { mineru_token: value }) + await refreshModelSettings() + showToast(service === 'deepseek' ? '校内 DeepSeek Key 已保存' : 'OCR-MinerU Key 已保存', 'success') + } catch (error) { + showToast(error instanceof Error ? error.message : '保存失败,请重试', 'error') + } finally { + setBusy(null) + } + } + + const test = async (service: Service, value?: string) => { + if (busy) return + setBusy(`${service}-test`) + try { + if (service === 'deepseek') await testDeepSeek(value) + else await testMinerU(value) + showToast(service === 'deepseek' + ? '校内 DeepSeek 连接成功' + : 'OCR-MinerU 连接成功,实际解析仍受额度与任务影响', 'success') + } catch (error) { + showToast(error instanceof Error ? error.message : '连接失败,请检查 Key 或服务可用性', 'error') + } finally { + setBusy(null) + } + } + + const loading = modelSettings === null + + return ( +
+

+ + API 配置 +

+ {loading ? ( +

+ + 正在读取配置… +

+ ) : ( +
+ save('deepseek', value)} + onTest={(value) => test('deepseek', value)} + /> + save('mineru', value)} + onTest={(value) => test('mineru', value)} + /> +
+ )} +
+ +

+ 上述 Key 将保存到您的账户,完整 Key 同时保存在本机浏览器中;在其他电脑配置的 Key 在本机只能显示打码样式。 +

+
+
+ ) +} diff --git a/frontend/src/components/tabs/ProfileTab/ApiConfigModal.tsx b/frontend/src/components/tabs/ProfileTab/ApiConfigModal.tsx new file mode 100644 index 0000000..ef5ed11 --- /dev/null +++ b/frontend/src/components/tabs/ProfileTab/ApiConfigModal.tsx @@ -0,0 +1,72 @@ +/** 未配置 API Key 时的引导弹窗:DeepSeek 与 OCR-MinerU 都需配置,可跳转个人中心。 */ +import { AlertCircle, ArrowRight, KeyRound, X } from 'lucide-react' +import { useApp } from '../../../store/AppContext' + +export default function ApiConfigModal() { + const { apiConfigOpen, closeApiConfigModal, setActiveTab, modelSettings } = useApp() + if (!apiConfigOpen) return null + const missing = [ + !modelSettings?.deepseek_key_configured && '校内 DeepSeek Key(出题、对话必需)', + !modelSettings?.mineru_token_configured && 'OCR-MinerU Key(扫描件解析、创建题库必需)', + ].filter(Boolean) as string[] + return ( +
+
e.stopPropagation()} + role="alertdialog" + aria-label="API 配置提醒" + > +
+

+ + 需要配置 API Key +

+ +
+
+

+ + 首次使用请先在「个人中心 → API 配置」中保存以下两项凭据: +

+
    + {missing.map((item) =>
  • {item}
  • )} +
+

+ 未配置校内 DeepSeek Key 时智能出题无法发送;未配置 OCR-MinerU Key 时无法上传扫描件创建题库。 +

+
+
+ + +
+
+
+ ) +} diff --git a/frontend/src/components/tabs/ProfileTab/index.tsx b/frontend/src/components/tabs/ProfileTab/index.tsx index d85bbf7..4502ee8 100644 --- a/frontend/src/components/tabs/ProfileTab/index.tsx +++ b/frontend/src/components/tabs/ProfileTab/index.tsx @@ -1,20 +1,22 @@ -/** 个人中心页:个人资料与账号安全。头像为系统默认,不可修改。 */ +/** 个人中心页:资料头部、安全管理与 API 配置。头像为系统默认,不可修改。 */ import { useRef, useState } from 'react' import { BadgeCheck, - Building2, + Check, + Headset, + KeyRound, Loader2, + Lock, Pencil, - Save, - ShieldCheck, User, - UserRound, X, } from 'lucide-react' import { useApp } from '../../../store/AppContext' +import { ApiConfigCard } from './ApiConfigCard' import { SecuritySettings } from './SecuritySettings' -import { changePasswordCurrent, validateNewPassword } from '../../../api/auth' +import { changePasswordCurrent, validateNewPassword, getAuthConfig } from '../../../api/auth' +import type { AuthConfig } from '../../../api/auth' import { useAuth } from '../../../store/AuthContext' import { getSessionGeneration } from '../../../api/session' @@ -23,42 +25,39 @@ export default function ProfileTab() { const { user, setAuthNotice } = useAuth() const session = useRef(getSessionGeneration()) - const [profileError, setProfileError] = useState('') const [pwdError, setPwdError] = useState('') - const reportProfileError = (message: string) => { setProfileError(message); showToast(message, 'error') } const reportPasswordError = (message: string) => { setPwdError(message); showToast(message, 'error') } + // 昵称编辑:与右上角昵称(profile.name)自动同步 const [editing, setEditing] = useState(false) - const [draft, setDraft] = useState({ name: profile.name, gender: profile.gender, phone: profile.phone, email: profile.email }) + const [draftName, setDraftName] = useState('') const [savingProfile, setSavingProfile] = useState(false) const [pwdOpen, setPwdOpen] = useState(false) const [pwdOld, setPwdOld] = useState('') const [pwdNew, setPwdNew] = useState('') const [pwdConfirm, setPwdConfirm] = useState('') const [savingPwd, setSavingPwd] = useState(false) + const [contactOpen, setContactOpen] = useState(false) + const [contact, setContact] = useState(null) const startEdit = () => { - setProfileError('') - setDraft({ name: profile.name, gender: profile.gender, phone: profile.phone, email: profile.email }) + setDraftName(profile.name) setEditing(true) } const saveEdit = async () => { if (savingProfile) return - if (!draft.name.trim()) { reportProfileError('昵称不能为空'); return } - if (draft.phone.trim() && !/^1[0-9]{10}$/.test(draft.phone.trim())) { reportProfileError('请输入正确的 11 位手机号码'); return } - setProfileError('') + if (!draftName.trim()) { showToast('昵称不能为空', 'error'); return } setSavingProfile(true) try { - await updateProfile({ name: draft.name.trim(), gender: draft.gender, phone: draft.phone.trim() }) + await updateProfile({ name: draftName.trim() }) setEditing(false) - showToast('个人信息已保存', 'success') - } catch (error) { reportProfileError(error instanceof Error ? error.message : '保存失败') } - finally { setSavingProfile(false) } + showToast('昵称已保存', 'success') + } catch (error) { + showToast(error instanceof Error ? error.message : '保存失败', 'error') + } finally { setSavingProfile(false) } } - const patchDraft = (patch: Partial) => setDraft((prev) => ({ ...prev, ...patch })) - const submitPassword = async () => { if (savingPwd) return if (!pwdOld) { reportPasswordError('请输入当前密码'); return } @@ -82,12 +81,19 @@ export default function ProfileTab() { } } + const openContact = () => { + setContactOpen(true) + if (!contact) { + void getAuthConfig().then(setContact).catch(() => setContact(null)) + } + } + const fieldCls = 'block w-full rounded-lg border border-line bg-white px-3 py-2 text-sm text-ink outline-none transition-colors focus:border-primary' return (
- {/* 页面小标题 */} + {/* 页面小标题(复用原标签容器样式) */}
@@ -97,8 +103,7 @@ export default function ProfileTab() {
{/* 头部信息卡 */} -
- {/* 头像:系统默认(昵称首字),不可修改 */} +
{profile.name.charAt(0)} @@ -111,116 +116,83 @@ export default function ProfileTab() {
-
- {profile.name} - {profile.identity} -
-

账号 ID:{profile.teacherId}

-
- -
-

- - 身份信息: - {profile.identity} -

-

- - 学校认证: - {profile.school} -

-
-
- - {/* 基本信息 */} -
-
-

- - 基本信息 -

{editing ? ( - +
+ setDraftName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && !e.nativeEvent.isComposing) void saveEdit() + if (e.key === 'Escape') setEditing(false) + }} + className="w-44 rounded-lg border border-line bg-white px-3 py-1.5 text-lg font-bold text-ink outline-none focus:border-primary" + /> + + +
) : ( - +
+ {profile.name} + +
)} -
- - {profileError &&

{profileError}

} -
-
- 登录账号 - {user?.username} -
-
- 昵称 - {editing ? ( - patchDraft({ name: e.target.value })} className={fieldCls} /> - ) : ( - {profile.name} - )} -
-
- 性别 - {editing ? ( - - ) : ( - - - {profile.gender || '未填写'} - - )} -
-
- 手机号码 - {editing ? ( - patchDraft({ phone: e.target.value })} className={fieldCls} /> - ) : ( - {profile.phone || '未填写'} - )} +
+ ID:{profile.teacherId} + + + 身份:{profile.identity} +
-
- 邮箱(可选) - {user?.email ? `${user.email}(${user.emailVerified ? '已验证' : '待验证'},通过账号安全管理)` : '未绑定,可在下方账号安全中绑定'} +
+ 登录账号 + {profile.teacherId} + + 邮箱(可选) + + {user?.email + ? `${user.email}(${user.emailVerified ? '已验证' : '待验证'},在下方账号安全管理)` + : '未绑定,可在下方账号安全中绑定'} +
-

性别和手机号码为可选资料;选择“未填写”或清空号码后保存可移除对应资料。

- + {/* 账号安全:学工号资料、邮箱绑定与修改密码入口,回归依赖 region 内顺序 */}
-

- - 修改密码 -

-
-
-

修改密码

-

修改后需要重新登录

-
+ {pwdError &&

{pwdError}

} +
+
+ {/* API 配置 */} + + {/* 修改密码弹窗 */} {pwdOpen && (
setPwdOpen(false)}>
e.stopPropagation()}>
-

修改密码

+

+ + 修改密码 +

@@ -293,6 +280,38 @@ export default function ProfileTab() {
)} + + {/* 联系管理员弹窗 */} + {contactOpen && ( +
setContactOpen(false)}> +
e.stopPropagation()}> +
+

+ + 联系管理员 +

+ +
+
+

+ + {contact?.admin_contact?.trim() || '请联系本校或平台管理员获取账号、重置密码或处理账号问题。'} +

+
+
+ +
+
+
+ )}
) } diff --git a/frontend/src/store/AppContext.tsx b/frontend/src/store/AppContext.tsx index b933499..da91cee 100644 --- a/frontend/src/store/AppContext.tsx +++ b/frontend/src/store/AppContext.tsx @@ -31,7 +31,14 @@ import type { AuthRole, AuthUser } from '../api/auth' const isChatMode = (value: string): value is ChatMode => value in CHAT_MODE_LABELS const QUESTION_DELETE_BATCH_SIZE = 200 -export type TabKey = 'generate' | 'preview' | 'bank' | 'records' | 'fav' | 'space' | 'me' | 'settings' +interface ChatTurn { + requestId: string + sessionId: string + bankId: string + docId: string +} + +export type TabKey = 'generate' | 'preview' | 'bank' | 'records' | 'fav' | 'space' | 'me' /** 历史会话侧边栏列表项(来自后端,按账号隔离) */ export interface ChatSessionSummary { @@ -50,7 +57,7 @@ function buildProfile(user: AuthUser | null): TeacherProfile { gender: user?.gender === '男' || user?.gender === '女' ? user.gender : '', phone: user?.phone ?? '', email: user?.email ?? '', - teacherId: user?.userNo ?? '', + teacherId: user?.username ?? '', school: user?.school ?? '', identity: user?.identity ?? '', } @@ -86,11 +93,12 @@ interface AppState { /** 删除受理后立即清理选中项与缓存,阻止旧请求重新写入。 */ invalidateDocument: (bankId: string, documentId: string) => void - /** 个人模型设置页的未保存提醒 */ - hasUnsavedChanges: boolean - setHasUnsavedChanges: (v: boolean) => void - isSettingsSaving: boolean - setIsSettingsSaving: (saving: boolean) => void + /** 个人 API 配置(脱敏);未配置 DeepSeek Key 时出题被拦截 */ + modelSettings: api.ModelSettings | null + refreshModelSettings: () => Promise + /** 未配置 API 时的引导弹窗 */ + apiConfigOpen: boolean + closeApiConfigModal: () => void generationRecoveryError: string | null resetGenerationRecovery: () => void @@ -213,6 +221,7 @@ interface AppState { sendChat: (text: string, images?: string[], opts?: { switchOnly?: boolean; mode?: ChatMode }) => Promise /** 中止当前对话请求(服务端仍会跑完,前端不再等结果) */ pauseChat: () => void + chatPauseStatus: 'pending' | 'failed' | null /** 回退到这条消息重新发送 */ retryChat: (messageId: string) => void /** 把这条消息放回输入框继续编辑 */ @@ -264,6 +273,7 @@ export function AppProvider({ children }: { children: ReactNode }) { const [chatProgress, setChatProgress] = useState<{ percent: number; stage: string } | null>(null) const [chatStartedAt, setChatStartedAt] = useState(null) const [botThinking, setBotThinking] = useState(false) + const [chatPauseStatus, setChatPauseStatus] = useState<'pending' | 'failed' | null>(null) const [inputDraft, setInputDraft] = useState('') const [chatImages, setChatImages] = useState([]) const [mode, setModeState] = useState('generate') @@ -278,23 +288,19 @@ export function AppProvider({ children }: { children: ReactNode }) { const [bankNotifUnread, setBankNotifUnread] = useState(0) const [bankNotifItems, setBankNotifItems] = useState([]) const [pendingSpacePaper, setPendingSpacePaper] = useState<{ spaceId: string; paperId: string } | null>(null) - // 个人模型设置页的未保存提醒 - const [hasUnsavedChanges, setHasUnsavedChangesState] = useState(false) - const [isSettingsSaving, setIsSettingsSavingState] = useState(false) - const settingsDirtyRef = useRef(false) - const settingsSavingRef = useRef(false) - const setHasUnsavedChanges = useCallback((dirty: boolean) => { - settingsDirtyRef.current = dirty - setHasUnsavedChangesState(dirty) - }, []) - const setIsSettingsSaving = useCallback((saving: boolean) => { - settingsSavingRef.current = saving - setIsSettingsSavingState(saving) - }, []) + // 个人 API 配置:登录后读取一次;未配置 DeepSeek Key 时弹出引导并拦截出题 + const [modelSettings, setModelSettings] = useState(null) + const [apiConfigOpen, setApiConfigOpen] = useState(false) + const apiConfigPromptedRef = useRef(false) + const activeBatchRef = useRef(null) const chatSessionRef = useRef<{ id: string; bankId: string; docId: string } | null>(null) const chatAbortRef = useRef(null) const chatBusyRef = useRef(false) + const activeChatTurn = useRef(null) + const pendingChatPause = useRef(null) + const chatPauseController = useRef(null) + const chatPauseKey = user ? `mathcraft:chat-pause:${user.userId}` : null const chatVersionRef = useRef(0) const messageIdRef = useRef(0) const imageVersionRef = useRef(0) @@ -323,12 +329,26 @@ export function AppProvider({ children }: { children: ReactNode }) { [], ) + const refreshModelSettings = useCallback(async () => { + const fresh = await api.getModelSettings() + if (!sessionIsCurrent()) return + setModelSettings(fresh) + const missing = !fresh.deepseek_key_configured || !fresh.mineru_token_configured + if (missing && !apiConfigPromptedRef.current) { + apiConfigPromptedRef.current = true + setApiConfigOpen(true) + } + }, [sessionIsCurrent]) + const closeApiConfigModal = useCallback(() => setApiConfigOpen(false), []) + useEffect(() => { mounted.current = true return () => { mounted.current = false if (chatPollRef.current !== null) window.clearInterval(chatPollRef.current) chatAbortRef.current?.abort() + chatPauseController.current?.abort() + chatPauseController.current = null confirmRequestRef.current?.abort() } }, []) @@ -353,18 +373,14 @@ export function AppProvider({ children }: { children: ReactNode }) { const setActiveTab = useCallback((tab: TabKey): boolean => { if (tab === activeTabRef.current) return true - if (settingsSavingRef.current) { - showToast('配置正在保存,请等待完成后再离开', 'error') - return false - } - if (settingsDirtyRef.current && !window.confirm('有未保存的模型配置,离开将丢弃修改。确定离开吗?')) return false activeTabRef.current = tab setActiveTabState(tab) return true - }, [showToast]) + }, []) // 同步失效会话回调,防止清空、切库或切文档后的旧结果回填。 const resetChat = useCallback(() => { + if (pendingChatPause.current) return chatVersionRef.current += 1 previewVersionRef.current += 1 sessionLoadingRef.current = false @@ -373,6 +389,7 @@ export function AppProvider({ children }: { children: ReactNode }) { chatAbortRef.current?.abort() confirmRequestRef.current?.abort() chatAbortRef.current = null + activeChatTurn.current = null confirmRequestRef.current = null chatSessionRef.current = null chatBusyRef.current = false @@ -655,7 +672,8 @@ export function AppProvider({ children }: { children: ReactNode }) { setKbs(bankRows.filter(bank => bank.status === 'active').map(api.mapBankToKnowledgeBase)) await Promise.all([loadFavorites(), loadRecords(), refreshSpaces(), loadSessions()]) if (!sessionIsCurrent()) return - if (restoreHistory && latest.batch_id && version === previewVersionRef.current && !isClearing()) { + if (restoreHistory && latest.batch_id && version === previewVersionRef.current + && !isClearing() && !pendingChatPause.current) { activeBatchRef.current = latest.batch_id setQuestions(latest.questions.map(api.mapQuestion)) } @@ -665,9 +683,14 @@ export function AppProvider({ children }: { children: ReactNode }) { })() }, [user, loadFavorites, loadRecords, loadSessions, refreshSpaces, sessionIsCurrent, showToast, isClearing]) + useEffect(() => { + if (!user) return + void refreshModelSettings().catch(() => undefined) + }, [user, refreshModelSettings]) + const selectKb = useCallback( (id: string) => { - if (!sessionIsCurrent()) return + if (!sessionIsCurrent() || pendingChatPause.current) return if (selectedKbRef.current !== id || selectedDocRef.current) resetChat() selectedDocRef.current = '' const version = ++documentRequestVersion.current @@ -690,7 +713,7 @@ export function AppProvider({ children }: { children: ReactNode }) { const selectDoc = useCallback( (id: string) => { - if (!sessionIsCurrent()) return + if (!sessionIsCurrent() || pendingChatPause.current) return if (selectedDocRef.current !== id) resetChat() selectedDocRef.current = id pendingDocumentSelection.current = null @@ -718,17 +741,35 @@ export function AppProvider({ children }: { children: ReactNode }) { ) const setMode = useCallback((next: ChatMode) => { - if (!sessionIsCurrent() || sessionLoadingRef.current || clearQuestionsFlight.current + if (!sessionIsCurrent() || sessionLoadingRef.current || pendingChatPause.current || clearQuestionsFlight.current || chatBusyRef.current || confirmRequestRef.current || pendingConfirmRef.current) return setModeState(next) setModeVisible(true) setModeSuggested(null) }, [sessionIsCurrent]) + const applyChatResult = useCallback((res: api.ChatMessageResult, previewVersion: number, appendReply = true) => { + setSessionMode(res.mode) + setModeVisible(res.kind !== 'reply') + setModeSuggested( + res.kind === 'mode_mismatch' && res.suggested_template + && isChatMode(res.suggested_template) ? res.suggested_template : null, + ) + setPendingConfirm(res.confirm ?? null) + if (appendReply) setMessages((prev) => [...prev, { id: `m-${++messageIdRef.current}`, role: 'assistant', text: res.reply }]) + if (res.questions.length && previewVersion === previewVersionRef.current) { + const incoming = res.questions.map(api.mapQuestion) + setQuestions((prev) => dedupeQuestions(prev, incoming)) + activeBatchRef.current = res.batch_id + setSelectedIds([]) + showToast(`已生成 ${incoming.length} 道题目,已合并到「题目预览」`) + } + }, [setPendingConfirm, showToast]) + const sendChat = useCallback( async (text: string, images: string[] = [], opts?: { switchOnly?: boolean; mode?: ChatMode }) => { const trimmed = text.trim() - if ((!trimmed && !images.length) || sessionLoadingRef.current || clearQuestionsFlight.current + if ((!trimmed && !images.length) || sessionLoadingRef.current || pendingChatPause.current || clearQuestionsFlight.current || generating || generationRecoveryError || chatBusyRef.current || confirmRequestRef.current || pendingConfirmRef.current || !sessionIsCurrent()) return if (selectedKbRef.current !== selectedKbId || selectedDocRef.current !== selectedDocId) return @@ -736,6 +777,11 @@ export function AppProvider({ children }: { children: ReactNode }) { showToast('请先在右侧选择知识库文档,才能基于知识库出题') return } + if (modelSettings && !modelSettings.deepseek_key_configured) { + apiConfigPromptedRef.current = true + setApiConfigOpen(true) + return + } const effectiveMode = opts?.mode ?? mode const version = chatVersionRef.current const previewVersion = ++previewVersionRef.current @@ -770,6 +816,8 @@ export function AppProvider({ children }: { children: ReactNode }) { } const sessionId = session.id if (!isActive()) return + const requestId = crypto.randomUUID() + activeChatTurn.current = { requestId, sessionId, bankId: session.bankId, docId: session.docId } poll = window.setInterval(() => { if (!isActive()) return void api.getChatProgress(sessionId, controller.signal).then((progress) => { @@ -783,27 +831,10 @@ export function AppProvider({ children }: { children: ReactNode }) { chatPollRef.current = poll const res = await api.sendChatMessage( sessionId, trimmed, questions.map((q) => q.stem), controller.signal, - images, effectiveMode, opts?.switchOnly ?? false, + images, effectiveMode, opts?.switchOnly ?? false, requestId, ) if (!isActive()) return - setSessionMode(res.mode) - setModeVisible(res.kind !== 'reply') - // 只接受合法业务模式:后端异常或历史版本传来的非法值直接忽略,避免卡死输入区 - setModeSuggested( - res.kind === 'mode_mismatch' && res.suggested_template - && isChatMode(res.suggested_template) ? res.suggested_template : null, - ) - // nullish 兜底:后端历史响应缺 confirm 字段时不能让 undefined 混进状态, - // 禁用判断都是「!== null」,undefined 会把发送、重生成与历史切换永久锁死 - setPendingConfirm(res.confirm ?? null) - setMessages((prev) => [...prev, { id: `m-${++messageIdRef.current}`, role: 'assistant', text: res.reply }]) - if (res.questions.length && previewVersion === previewVersionRef.current) { - const incoming = res.questions.map(api.mapQuestion) - setQuestions((prev) => dedupeQuestions(prev, incoming)) - activeBatchRef.current = res.batch_id - setSelectedIds([]) - showToast(`已生成 ${incoming.length} 道题目,已合并到「题目预览」`) - } + applyChatResult(res, previewVersion) } catch (error: unknown) { if (!isActive()) return setMessages((prev) => [...prev, { @@ -815,6 +846,7 @@ export function AppProvider({ children }: { children: ReactNode }) { if (isActive()) { chatPollRef.current = null chatAbortRef.current = null + activeChatTurn.current = null chatBusyRef.current = false setChatProgress(null) setChatStartedAt(null) @@ -825,7 +857,7 @@ export function AppProvider({ children }: { children: ReactNode }) { } }, [mode, loadSessions, selectedDocId, selectedKbId, questions, generating, generationRecoveryError, - sessionIsCurrent, setPendingConfirm, showToast], + applyChatResult, sessionIsCurrent, showToast, modelSettings], ) const addChatImages = useCallback((files: File[]) => { @@ -868,7 +900,7 @@ export function AppProvider({ children }: { children: ReactNode }) { const confirmOperation = useCallback(async (accepted: boolean) => { const target = pendingConfirmRef.current const sessionId = chatSessionRef.current?.id - if (!sessionIsCurrent() || sessionLoadingRef.current || clearQuestionsFlight.current + if (!sessionIsCurrent() || sessionLoadingRef.current || pendingChatPause.current || clearQuestionsFlight.current || !target || !sessionId || confirmRequestRef.current || chatBusyRef.current) return const version = chatVersionRef.current @@ -907,30 +939,130 @@ export function AppProvider({ children }: { children: ReactNode }) { } }, [loadFavorites, loadRecords, sessionIsCurrent, setPendingConfirm, showToast]) - const pauseChat = useCallback(() => { - if (!sessionIsCurrent() || !chatBusyRef.current) return - const sessionId = chatSessionRef.current?.id + const settleChatPause = useCallback(async (turn: ChatTurn) => { + if (!sessionIsCurrent() || chatPauseController.current) return + const controller = new AbortController() + chatPauseController.current = controller + pendingChatPause.current = turn + chatBusyRef.current = true const version = chatVersionRef.current + const previewVersion = ++previewVersionRef.current + const isActive = () => sessionIsCurrent() && !controller.signal.aborted + && chatPauseController.current === controller + setBotThinking(true) + setChatPauseStatus('pending') + try { + if (chatPauseKey) sessionStorage.setItem(chatPauseKey, JSON.stringify(turn)) + const requestSignal = () => AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]) + let state = await api.cancelChat(turn.sessionId, turn.requestId, requestSignal()) + while (isActive() && (state.status === 'running' || !state.execution_finished)) { + await new Promise(resolve => window.setTimeout(resolve, 750)) + if (!isActive()) return + state = await api.getChatTurn(turn.sessionId, turn.requestId, requestSignal()) + } + if (!isActive()) return + if (state.status === 'done' && !state.result) throw new Error('未能恢复本轮已保存的结果') + const restoring = chatSessionRef.current === null && version === chatVersionRef.current + if (restoring) { + const signal = requestSignal() + const [detail, documents] = await Promise.all([ + api.getChatSession(turn.sessionId, signal), + api.listDocuments(turn.bankId, signal), + ]) + let previous: { batch_id: string | null; questions: api.ApiQuestion[] } | null = null + if (!state.batch_id) { + const previousBatch = [...detail.messages].reverse().find(message => message.batch_id)?.batch_id + if (previousBatch) { + const page = await api.listQuestions({ batch_id: previousBatch, page_size: 100 }, requestSignal()) + previous = { batch_id: previousBatch, questions: page.items } + } else { + previous = await api.latestBatch(undefined, undefined, requestSignal()) + } + } + if (!isActive()) return + if (version === chatVersionRef.current) { + chatSessionRef.current = { id: turn.sessionId, bankId: turn.bankId, docId: turn.docId } + selectedKbRef.current = turn.bankId + selectedDocRef.current = turn.docId + setActiveSessionId(turn.sessionId) + setSelectedKbId(turn.bankId) + setSelectedDocId(turn.docId) + applyDocumentRows(turn.bankId, documents) + setModeState(detail.mode) + setSessionMode(detail.mode) + setModeVisible(detail.messages.length === 0) + if (previous && previewVersion === previewVersionRef.current) { + setQuestions(previous.questions.map(api.mapQuestion)) + activeBatchRef.current = previous.batch_id + } + setMessages(detail.messages.map(message => ({ + id: message.id, role: message.role, text: message.text, + }))) + } + } + if (state.result && chatSessionRef.current?.id === turn.sessionId + && version === chatVersionRef.current) { + applyChatResult(state.result, previewVersion, !restoring) + showToast('本轮已完成,已恢复结果') + } else if (chatSessionRef.current?.id === turn.sessionId && version === chatVersionRef.current) { + const message = state.status === 'canceled' ? '已暂停本次生成。' : '本轮处理已结束,请重新发送。' + setMessages(prev => [...prev, { + id: `m-${++messageIdRef.current}`, role: 'assistant', text: message, + }]) + } + if (chatPauseKey) sessionStorage.removeItem(chatPauseKey) + pendingChatPause.current = null + chatBusyRef.current = false + setChatPauseStatus(null) + setBotThinking(false) + void loadSessions() + } catch (error: unknown) { + if (!isActive()) return + setChatPauseStatus('failed') + showToast(error instanceof Error ? error.message : '服务端暂停未确认', 'error') + } finally { + if (chatPauseController.current === controller) chatPauseController.current = null + } + }, [applyChatResult, applyDocumentRows, chatPauseKey, loadSessions, sessionIsCurrent, showToast]) + + const pauseChat = useCallback(() => { + if (!sessionIsCurrent() || chatPauseController.current + || (!chatBusyRef.current && !pendingChatPause.current)) return + const turn = pendingChatPause.current ?? activeChatTurn.current chatAbortRef.current?.abort() if (chatPollRef.current !== null) window.clearInterval(chatPollRef.current) chatPollRef.current = null chatAbortRef.current = null - chatBusyRef.current = false - setBotThinking(false) + activeChatTurn.current = null setChatProgress(null) setChatStartedAt(null) - setMessages((prev) => [...prev, { - id: `m-${++messageIdRef.current}`, role: 'assistant', text: '已暂停本次生成。', - }]) - if (sessionId) void api.cancelChat(sessionId).then(() => loadSessions()).catch((error: unknown) => { - if (sessionIsCurrent() && version === chatVersionRef.current && !chatBusyRef.current) { - showToast(error instanceof Error ? error.message : '服务端暂停未确认') + if (turn) { + void settleChatPause(turn) + } else { + chatBusyRef.current = false + setBotThinking(false) + } + }, [sessionIsCurrent, settleChatPause]) + + useEffect(() => { + if (!chatPauseKey) return + try { + const saved = sessionStorage.getItem(chatPauseKey) + if (!saved) return + const turn: Partial | null = JSON.parse(saved) + if (turn && typeof turn.requestId === 'string' && typeof turn.sessionId === 'string' + && typeof turn.bankId === 'string' && typeof turn.docId === 'string') { + void settleChatPause({ + requestId: turn.requestId, sessionId: turn.sessionId, bankId: turn.bankId, docId: turn.docId, + }) } - }) - }, [loadSessions, sessionIsCurrent, showToast]) + } catch (error: unknown) { + showToast(error instanceof Error ? error.message : '读取暂停记录失败', 'error') + } + }, [chatPauseKey, settleChatPause, showToast]) const retryChat = useCallback((messageId: string) => { - if (!sessionIsCurrent() || sessionLoadingRef.current || clearQuestionsFlight.current + if (!sessionIsCurrent() || sessionLoadingRef.current || pendingChatPause.current || clearQuestionsFlight.current || generating || generationRecoveryError || chatBusyRef.current || confirmRequestRef.current || pendingConfirmRef.current || !selectedDocId || !selectedKbId || selectedKbRef.current !== selectedKbId || selectedDocRef.current !== selectedDocId) return @@ -942,7 +1074,7 @@ export function AppProvider({ children }: { children: ReactNode }) { }, [messages, selectedDocId, selectedKbId, sendChat, sessionIsCurrent, generating, generationRecoveryError]) const editChat = useCallback((messageId: string) => { - if (!sessionIsCurrent() || sessionLoadingRef.current || clearQuestionsFlight.current + if (!sessionIsCurrent() || sessionLoadingRef.current || pendingChatPause.current || clearQuestionsFlight.current || chatBusyRef.current || confirmRequestRef.current || pendingConfirmRef.current) return const index = messages.findIndex((message) => message.id === messageId && message.role === 'user') if (index < 0) return @@ -957,7 +1089,7 @@ export function AppProvider({ children }: { children: ReactNode }) { const openSession = useCallback( async (target: ChatSessionSummary) => { const confirmInFlight = confirmRequestRef.current !== null - if (!sessionIsCurrent() || chatBusyRef.current || confirmInFlight + if (!sessionIsCurrent() || chatBusyRef.current || pendingChatPause.current || confirmInFlight || pendingConfirmRef.current !== null) return const version = ++chatVersionRef.current const previewVersion = ++previewVersionRef.current @@ -1052,7 +1184,7 @@ export function AppProvider({ children }: { children: ReactNode }) { /** 新建对话:回到欢迎态;当前会话保留在历史列表中 */ const startNewChat = useCallback(() => { - if (!sessionIsCurrent()) return + if (!sessionIsCurrent() || pendingChatPause.current) return if (!setActiveTab('generate')) return resetChat() }, [resetChat, sessionIsCurrent, setActiveTab]) @@ -1578,10 +1710,10 @@ export function AppProvider({ children }: { children: ReactNode }) { selectDoc, refreshKbs, invalidateDocument, - hasUnsavedChanges, - setHasUnsavedChanges, - isSettingsSaving, - setIsSettingsSaving, + modelSettings, + refreshModelSettings, + apiConfigOpen, + closeApiConfigModal, generating, generationClearing, generationRecoveryError, @@ -1668,6 +1800,7 @@ export function AppProvider({ children }: { children: ReactNode }) { removeChatImage, sendChat, pauseChat, + chatPauseStatus, chatProgress, chatStartedAt, retryChat, diff --git a/openapi.json b/openapi.json index 354e7c9..2ef4af3 100644 --- a/openapi.json +++ b/openapi.json @@ -2090,7 +2090,7 @@ "users" ], "summary": "Test Deepseek", - "description": "测试 DeepSeek 连接,失败仅返回固定脱敏提示。", + "description": "测试 DeepSeek 连接;body 提供输入值时优先测试该值,不落库。失败仅返回固定脱敏提示。", "operationId": "test_deepseek_api_users_me_model_settings_test_deepseek_post", "parameters": [ { @@ -2110,6 +2110,23 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModelTestBody" + }, + { + "type": "null" + } + ], + "title": "Body" + } + } + } + }, "responses": { "200": { "description": "Successful Response", @@ -2138,7 +2155,7 @@ "users" ], "summary": "测试 MinerU 连接与鉴权(不验证文件解析)", - "description": "只读验证已保存 MinerU 配置的连接与鉴权,不验证额度或实际文件解析。\n\n严格校验 HTTP、JSON 与业务状态,仅将明确成功或官方找不到探测任务视为通过。", + "description": "只读验证 MinerU 配置的连接与鉴权;body 提供输入值时优先测试该值,不落库。\n\n严格校验 HTTP、JSON 与业务状态,仅将明确成功或官方找不到探测任务视为通过。", "operationId": "test_mineru_api_users_me_model_settings_test_mineru_post", "parameters": [ { @@ -2158,6 +2175,23 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModelTestBody" + }, + { + "type": "null" + } + ], + "title": "Body" + } + } + } + }, "responses": { "200": { "description": "Successful Response", @@ -5254,7 +5288,9 @@ "description": "Successful Response", "content": { "application/json": { - "schema": {} + "schema": { + "$ref": "#/components/schemas/ChatMessageResponse" + } } } }, @@ -5405,6 +5441,75 @@ } } }, + "/api/chat/sessions/{session_id}/requests/{request_id}": { + "get": { + "tags": [ + "chat" + ], + "summary": "Read Chat Request", + "description": "读取属于本会话的指定轮次及其已提交回复。", + "operationId": "read_chat_request_api_chat_sessions__session_id__requests__request_id__get", + "parameters": [ + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Session Id" + } + }, + { + "name": "request_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid", + "title": "Request Id" + } + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Authorization" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatRequestResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, "/api/chat/sessions/{session_id}/cancel": { "post": { "tags": [ @@ -5423,6 +5528,23 @@ "title": "Session Id" } }, + { + "name": "request_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string", + "format": "uuid" + }, + { + "type": "null" + } + ], + "title": "Request Id" + } + }, { "name": "Authorization", "in": "header", @@ -5445,7 +5567,20 @@ "description": "Successful Response", "content": { "application/json": { - "schema": {} + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatRequestResponse" + }, + { + "type": "object", + "additionalProperties": { + "type": "boolean" + } + } + ], + "title": "Response Cancel Generation Api Chat Sessions Session Id Cancel Post" + } } } }, @@ -8704,6 +8839,18 @@ }, "ChatMessageBody": { "properties": { + "request_id": { + "anyOf": [ + { + "type": "string", + "format": "uuid" + }, + { + "type": "null" + } + ], + "title": "Request Id" + }, "message": { "type": "string", "maxLength": 2048, @@ -8745,6 +8892,331 @@ ], "title": "ChatMessageBody" }, + "ChatMessageResponse": { + "properties": { + "reply": { + "type": "string", + "title": "Reply" + }, + "questions": { + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatSavedQuestion" + }, + { + "$ref": "#/components/schemas/Question" + } + ] + }, + "type": "array", + "title": "Questions" + }, + "done": { + "type": "boolean", + "title": "Done" + }, + "batch_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Batch Id" + }, + "slot_state": { + "additionalProperties": true, + "type": "object", + "title": "Slot State" + }, + "kind": { + "type": "string", + "enum": [ + "reply", + "mode_mismatch", + "mode_confirm" + ], + "title": "Kind" + }, + "mode": { + "type": "string", + "enum": [ + "generate", + "creative", + "qa", + "data" + ], + "title": "Mode" + }, + "mode_changed": { + "type": "boolean", + "title": "Mode Changed" + }, + "suggested_template": { + "anyOf": [ + { + "type": "string", + "enum": [ + "generate", + "creative", + "qa", + "data", + "none" + ] + }, + { + "type": "null" + } + ], + "title": "Suggested Template" + }, + "confirm": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatOperationPreview" + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "reply", + "questions", + "done", + "batch_id", + "slot_state", + "kind", + "mode", + "mode_changed", + "suggested_template", + "confirm" + ], + "title": "ChatMessageResponse", + "description": "消息接口与状态查询共用的已发布回复。" + }, + "ChatOperationPreview": { + "properties": { + "id": { + "type": "string", + "title": "Id" + }, + "action": { + "type": "string", + "enum": [ + "delete", + "update" + ], + "title": "Action" + }, + "entity": { + "type": "string", + "title": "Entity" + }, + "entity_label": { + "type": "string", + "title": "Entity Label" + }, + "affected": { + "type": "integer", + "title": "Affected" + }, + "samples": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Samples" + }, + "explanation": { + "type": "string", + "title": "Explanation" + } + }, + "type": "object", + "required": [ + "id", + "action", + "entity", + "entity_label", + "affected", + "samples", + "explanation" + ], + "title": "ChatOperationPreview", + "description": "已发布的操作确认预览。" + }, + "ChatRequestResponse": { + "properties": { + "status": { + "type": "string", + "enum": [ + "running", + "canceled", + "done", + "failed", + "interrupted" + ], + "title": "Status" + }, + "execution_finished": { + "type": "boolean", + "title": "Execution Finished" + }, + "batch_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Batch Id" + }, + "result": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatMessageResponse" + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "status", + "execution_finished", + "batch_id", + "result" + ], + "title": "ChatRequestResponse", + "description": "指定轮次的业务状态及执行退出事实。" + }, + "ChatSavedQuestion": { + "properties": { + "id": { + "type": "string", + "title": "Id" + }, + "type": { + "$ref": "#/components/schemas/QuestionType" + }, + "score": { + "type": "integer", + "title": "Score" + }, + "difficulty": { + "$ref": "#/components/schemas/Difficulty" + }, + "difficulty_score": { + "type": "number", + "title": "Difficulty Score" + }, + "difficulty_review": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Difficulty Review" + }, + "stem": { + "type": "string", + "title": "Stem" + }, + "options": { + "items": { + "additionalProperties": true, + "type": "object" + }, + "type": "array", + "title": "Options" + }, + "answer": { + "type": "string", + "title": "Answer" + }, + "analysis": { + "type": "string", + "title": "Analysis" + }, + "knowledge_point": { + "type": "string", + "title": "Knowledge Point" + }, + "starred": { + "type": "boolean", + "title": "Starred" + }, + "favorite_group_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Favorite Group Id" + }, + "doc_name": { + "type": "string", + "title": "Doc Name" + }, + "bank_id": { + "type": "string", + "title": "Bank Id" + }, + "document_id": { + "type": "string", + "title": "Document Id" + }, + "batch_id": { + "type": "string", + "title": "Batch Id" + }, + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + } + }, + "type": "object", + "required": [ + "id", + "type", + "score", + "difficulty", + "difficulty_score", + "difficulty_review", + "stem", + "options", + "answer", + "analysis", + "knowledge_point", + "starred", + "favorite_group_id", + "doc_name", + "bank_id", + "document_id", + "batch_id", + "created_at" + ], + "title": "ChatSavedQuestion", + "description": "题库中当前保存的对话题目。" + }, "ChatSessionCreateBody": { "properties": { "bank_id": { @@ -9858,6 +10330,37 @@ "type": "object", "title": "ModelSettingsBody" }, + "ModelTestBody": { + "properties": { + "deepseek_api_key": { + "anyOf": [ + { + "type": "string", + "maxLength": 128 + }, + { + "type": "null" + } + ], + "title": "Deepseek Api Key" + }, + "mineru_token": { + "anyOf": [ + { + "type": "string", + "maxLength": 128 + }, + { + "type": "null" + } + ], + "title": "Mineru Token" + } + }, + "type": "object", + "title": "ModelTestBody", + "description": "连接测试的可选输入值;提供时优先测试该值,不落库。" + }, "NotificationReadBody": { "properties": { "ids": { @@ -11770,6 +12273,18 @@ "maximum": 100.0, "minimum": 1.0, "title": "Count" + }, + "difficulty": { + "anyOf": [ + { + "type": "string", + "pattern": "^(低|中|高|地狱)$" + }, + { + "type": "null" + } + ], + "title": "Difficulty" } }, "type": "object", @@ -12062,4 +12577,4 @@ } } } -} +} \ No newline at end of file diff --git a/tools/gen_api_docs.py b/tools/gen_api_docs.py index 18fc1c3..376dad1 100644 --- a/tools/gen_api_docs.py +++ b/tools/gen_api_docs.py @@ -59,7 +59,8 @@ def main() -> int: "单 worker 启动恢复将未完成的持久任务及运行中的会话标为 `interrupted`,", "同一事务将对应仍为 `accepted`/`running` 的台账标为 `unknown`,", "错误码为 `EXECUTION_INTERRUPTED`;无持久任务或会话关联的历史台账不被扫描。\n\n", - "对话支持快速出题、创新命题、知识答疑和数据管理四种模式;", + "对话支持快速出题、创新命题、知识答疑和数据管理四种模式。", + "对话消息携带 request_id 时可按轮次暂停与查询结果;", "参数化异步出题支持 request_id 幂等受理、按任务取消及执行退出确认;", "取消中仍占用生成门禁,一键清空的完整语义见", "[快速出题取消与清空](implementation/快速出题取消与清空.md)。",