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({
留空表示保留原凭据;勾选清除后点击保存。测试只使用已保存的配置,请先保存修改。
- {busy === 'load' &&{error}
} - {notice &&{notice}
} - {!model && busy === null && } -有未保存的修改,请先保存再测试。
} - {model &&系统向量模型(由管理员配置):{model.embedding_model}
-系统重排模型(由管理员配置):{model.rerank_model}
-管理个人 DeepSeek 与 MinerU 服务配置。题库配置请前往题库管理。
-{hint}
+
+
+ 上述 Key 将保存到您的账户,完整 Key 同时保存在本机浏览器中;在其他电脑配置的 Key 在本机只能显示打码样式。 +
+
+
+ 未配置校内 DeepSeek Key 时智能出题无法发送;未配置 OCR-MinerU Key 时无法上传扫描件创建题库。 +
+账号 ID:{profile.teacherId}
-
-
-
{profileError}
} -性别和手机号码为可选资料;选择“未填写”或清空号码后保存可移除对应资料。
- + {/* 账号安全:学工号资料、邮箱绑定与修改密码入口,回归依赖 region 内顺序 */}修改密码
-修改后需要重新登录
-{pwdError}
} +
+