From bb624ef85aeb26815cccdf1a6ddc0effd7d6b854 Mon Sep 17 00:00:00 2001 From: Logic <241731638@m.gduf.edu.cn> Date: Thu, 19 Nov 2026 14:15:13 +0800 Subject: [PATCH 1/8] =?UTF-8?q?fix(chat):=20=E7=AD=89=E5=BE=85=E6=9A=82?= =?UTF-8?q?=E5=81=9C=E7=A1=AE=E8=AE=A4=E5=90=8E=E5=86=8D=E5=BC=80=E6=94=BE?= =?UTF-8?q?=E6=B8=85=E7=A9=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按请求标识确认原轮次结束和执行器退出,避免清空时遗漏已经提交但尚未显示的题目。恢复抢先提交的回复和现存题目,保持预览清空按确认时的题目范围执行。 同步接口契约及设计文档,并覆盖取消先于发送、提交先于取消、刷新恢复及历史参数化出题的取消路径。 --- README.md | 2 +- .../versions/q2d3e4f56789_chat_requests.py | 31 ++ backend/app/api/chat.py | 269 ++++++++--- backend/app/models/__init__.py | 4 +- backend/app/models/chat.py | 21 +- backend/app/schemas/api.py | 62 ++- backend/app/services/generation.py | 8 +- backend/tests/test_acid_migration.py | 12 +- backend/tests/test_agent_main_migration.py | 4 +- backend/tests/test_chat_requests.py | 162 +++++++ backend/tests/test_ops_runs_migration.py | 2 +- docs/api.md | 5 +- ...73\347\272\277\346\225\264\345\220\210.md" | 8 +- ...10\344\270\216\346\270\205\347\251\272.md" | 9 +- frontend/merge-frontend-regression.mjs | 7 +- frontend/merge-session-cases.mjs | 68 +++ frontend/src/api/backend.ts | 38 +- frontend/src/components/layout/TabBar.tsx | 4 +- .../components/tabs/GenerateTab/ChatInput.tsx | 28 +- frontend/src/store/AppContext.tsx | 209 +++++++-- openapi.json | 444 +++++++++++++++++- tools/gen_api_docs.py | 3 +- 22 files changed, 1260 insertions(+), 140 deletions(-) create mode 100644 backend/alembic/versions/q2d3e4f56789_chat_requests.py create mode 100644 backend/tests/test_chat_requests.py diff --git a/README.md b/README.md index 5c1f678..6db4fc7 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ MathCraft 面向教师与学生,提供题库协作、文档解析与检索、 对话提供快速出题、创新命题、知识答疑和数据管理四模式,右侧历史会话支持继续已有对话。出题先命制题干,再独立解题生成答案、选项和解析,审核后按题型缺口尝试补齐;界面通过进度轮询等待结果。题目预览中勾选题目后可导出 Word,设置题型顺序、答案和解析的位置。 -试卷支持关闭和恢复作答,删除保留已有作答及成绩;出题任务状态存入 SQL,服务重启后未完成的任务标为中断,用户可重新发起。预览页一键清空只删除题目,保留对话;运行期间暂不可清空,后台取消和最终提交继续校验运行身份。 +试卷支持关闭和恢复作答,删除保留已有作答及成绩;出题任务状态存入 SQL,服务重启后未完成的任务标为中断,用户可重新发起。一键清空删除当前预览的题目并保留对话。生成期间和暂停待确认期间,清空按钮禁用。若暂停前本轮已保存,先恢复结果供用户查看和清空。 学习空间可在停止作答后移除尚无作答记录的发布;已有作答保留历史入口。删除未完成的题库与资料在管理页提供继续清理入口。 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..d67ac87 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,74 @@ 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,请到设置 → 模型与服务中填写", 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 +658,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 +687,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 +727,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 +780,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/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/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/schemas/api.py b/backend/app/schemas/api.py index 0a6b761..b209656 100644 --- a/backend/app/schemas/api.py +++ b/backend/app/schemas/api.py @@ -7,7 +7,7 @@ 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): @@ -139,6 +139,7 @@ class ChatSessionDetailResponse(BaseModel): class ChatMessageBody(BaseModel): + request_id: UUID | None = None message: str = Field( max_length=2048, description="消息文本;仅发送图片时可为空,文本与图片不可同时为空", ) @@ -185,6 +186,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/services/generation.py b/backend/app/services/generation.py index fd2471f..aa23e32 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 @@ -743,6 +743,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/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_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\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/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/merge-frontend-regression.mjs b/frontend/merge-frontend-regression.mjs index b7035b2..aec9081 100644 --- a/frontend/merge-frontend-regression.mjs +++ b/frontend/merge-frontend-regression.mjs @@ -191,7 +191,8 @@ async function mount(mode, role = 'teacher', memberRole = 'creator', format = 'T sendChatMessage: (...args) => h.chatReply({mode:args[5]}), confirmChat: () => ({reply:'操作已确认', done:true}), deleteChatSession: () => {}, batchDeleteQuestions: () => {}, - getChatProgress: () => ({active:true, percent:20, stage:'合成进度'}), cancelChat: () => {}, + getChatProgress: () => ({active:true, percent:20, stage:'合成进度'}), + cancelChat: () => ({status:'canceled', execution_finished:true, batch_id:null, result:null}), startGeneration: () => ({task_id:'fake-task'}), findGenerationRequest: () => ({task_id:'fake-task'}), cancelGeneration: () => ({done:true, execution_finished:true, status:'canceled', progress:0, @@ -1216,7 +1217,9 @@ async function prepareConfirmation(page, entity, action = 'delete') { await chat.waitForFunction(() => window.mergeApp.selectedDocId === 'doc-bank-A') await chat.evaluate(() => { window.mergeHarness.held.sendChatMessage = true; void window.mergeApp.sendChat('第一次') }) await chat.waitForFunction(() => window.mergeHarness.pending.sendChatMessage?.length === 1) - await chat.evaluate(() => { window.mergeApp.pauseChat(); void window.mergeApp.sendChat('第二次') }) + await chat.evaluate(() => window.mergeApp.pauseChat()) + await chat.waitForFunction(() => !window.mergeApp.botThinking) + await chat.evaluate(() => { void window.mergeApp.sendChat('第二次') }) await chat.waitForFunction(() => window.mergeHarness.pending.sendChatMessage.length === 2) await chat.evaluate(() => window.mergeHarness.finish('sendChatMessage', window.mergeHarness.chatReply({reply:'旧结果', mode:'data'}))) await chat.waitForFunction(() => window.mergeHarness.pending.sendChatMessage.length === 1) diff --git a/frontend/merge-session-cases.mjs b/frontend/merge-session-cases.mjs index 91aa8ea..ec7b2cc 100644 --- a/frontend/merge-session-cases.mjs +++ b/frontend/merge-session-cases.mjs @@ -172,6 +172,74 @@ export async function runChatHistoryCases({ providerCase, selectBank, settleRend assert.equal(await page.evaluate(() => window.mergeHarness.calls.some(c => c.name === 'batchDeleteQuestions')), false) }) + await providerCase('pause waits for server and restores a committed batch before clear', async page => { + await seed(page) + await page.evaluate(() => { + const h = window.mergeHarness + h.held.sendChatMessage = h.held.cancelChat = h.held.getChatTurn = true + void window.mergeApp.sendChat('等待生成结果') + }) + await page.waitForFunction(() => window.mergeHarness.pending.sendChatMessage?.length === 1) + await page.getByRole('button', {name:'暂停', exact:true}).click() + assert.equal(await page.getByRole('button', {name:'正在暂停', exact:true}).isDisabled(), true) + assert.equal(await page.getByRole('button', {name:'正在暂停', exact:true}).locator('svg').count(), 1) + await page.evaluate(() => window.mergeApp.setActiveTab('preview')) + assert.equal(await page.getByRole('button', {name:'一键清空', exact:true}).isDisabled(), true) + await page.evaluate(() => { + const h = window.mergeHarness + h.finish('cancelChat', {status:'done', execution_finished:false, batch_id:'late', result:null}) + }) + await page.waitForFunction(() => window.mergeHarness.pending.getChatTurn?.length === 1) + assert.equal(await page.getByRole('button', {name:'一键清空', exact:true}).isDisabled(), true) + await page.evaluate(() => { + const h = window.mergeHarness + h.finish('getChatTurn', {status:'done', execution_finished:true, batch_id:'late', + result:h.chatReply({reply:'已完成该轮', batch_id:'late', questions:[{id:'late-question'}]})}) + }) + await page.waitForFunction(() => !window.mergeApp.botThinking + && window.mergeApp.questions.some(question => question.id === 'late-question')) + await page.getByRole('button', {name:'一键清空', exact:true}).click() + await page.getByRole('button', {name:'确认清空', exact:true}).click() + await page.waitForFunction(() => window.mergeApp.questions.length === 0) + assert.equal(await page.evaluate(() => window.mergeApp.messages.some(m => m.text === '已完成该轮')), true) + assert.equal(await page.evaluate(() => window.mergeHarness.calls + .some(call => call.name === 'batchDeleteQuestions' && call.args[0].includes('late-question'))), true) + }) + + await providerCase('failed pause stays locked and refresh continues the original request', async page => { + await seed(page) + await page.evaluate(() => { + const h = window.mergeHarness + h.held.sendChatMessage = h.held.cancelChat = true + void window.mergeApp.sendChat('等待暂停确认') + }) + await page.waitForFunction(() => window.mergeHarness.pending.sendChatMessage?.length === 1) + await page.getByRole('button', {name:'暂停', exact:true}).click() + await page.waitForFunction(() => window.mergeHarness.pending.cancelChat?.length === 1) + await page.evaluate(() => window.mergeHarness.pending.cancelChat.shift().reject(new Error('断连'))) + await page.getByRole('button', {name:'重试暂停', exact:true}).waitFor() + await page.evaluate(() => window.mergeApp.setActiveTab('preview')) + assert.equal(await page.getByRole('button', {name:'一键清空', exact:true}).isDisabled(), true) + await page.evaluate(() => { + const h = window.mergeHarness + h.backend.latestBatch = () => ({batch_id:'preview-batch', questions:[{id:'preview-result'}]}) + h.generation += 1 + window.remountMerge() + }) + await page.waitForFunction(() => window.mergeHarness.pending.cancelChat?.length === 1) + const requestIds = await page.evaluate(() => ({ + sent: window.mergeHarness.calls.filter(call => call.name === 'sendChatMessage').at(-1).args[7], + paused: window.mergeHarness.calls.filter(call => call.name === 'cancelChat').map(call => call.args[1]), + })) + assert.deepEqual(requestIds.paused, [requestIds.sent, requestIds.sent]) + await page.evaluate(() => window.mergeHarness.finish('cancelChat', { + status:'canceled', execution_finished:true, batch_id:null, result:null, + })) + await page.waitForFunction(() => !window.mergeApp.botThinking && window.mergeApp.chatPauseStatus === null) + assert.equal(await page.evaluate(() => window.mergeApp.questions[0]?.id), 'preview-result') + assert.equal(await page.evaluate(() => window.mergeApp.docs.some(doc => doc.id === 'doc-bank-A')), true) + }) + await providerCase('preview clear batches at 200; partial failure keeps all local questions and favorites until retry succeeds', async page => { await page.evaluate(() => { const h = window.mergeHarness diff --git a/frontend/src/api/backend.ts b/frontend/src/api/backend.ts index bc4002a..4ed8f72 100644 --- a/frontend/src/api/backend.ts +++ b/frontend/src/api/backend.ts @@ -290,8 +290,8 @@ export function mapDocument(doc: ApiDocument): KbDocument & { api: ApiDocument } status: doc.status, stage: doc.stage, progress: doc.progress, api: doc } } -export async function listDocuments(bankId: string): Promise { - return request(`/api/banks/${bankId}/documents`) +export async function listDocuments(bankId: string, signal?: AbortSignal): Promise { + return request(`/api/banks/${bankId}/documents`, { signal }) } export async function getDocument(bankId: string, docId: string): Promise { @@ -479,11 +479,12 @@ export async function cancelGeneration(taskId: string): Promise { const params = new URLSearchParams() if (bankId) params.set('bank_id', bankId) if (documentId) params.set('document_id', documentId) - return request(`/api/generate/batches/latest?${params.toString()}`) + return request(`/api/generate/batches/latest?${params.toString()}`, { signal }) } export async function listQuestions(params: { @@ -492,12 +493,12 @@ export async function listQuestions(params: { document_id?: string page?: number page_size?: number -}): Promise<{ items: ApiQuestion[]; total: number }> { +}, signal?: AbortSignal): Promise<{ items: ApiQuestion[]; total: number }> { const search = new URLSearchParams() Object.entries(params).forEach(([k, v]) => { if (v !== undefined && v !== '') search.set(k, String(v)) }) - return request(`/api/questions?${search.toString()}`) + return request(`/api/questions?${search.toString()}`, { signal }) } export async function updateQuestionApi(q: Question): Promise { @@ -1072,8 +1073,8 @@ export interface BackendChatDetail { messages: ApiChatMessage[] } -export async function getChatSession(sessionId: string): Promise { - return request(`/api/chat/sessions/${sessionId}`) +export async function getChatSession(sessionId: string, signal?: AbortSignal): Promise { + return request(`/api/chat/sessions/${sessionId}`, { signal }) } export async function createChatSession(bankId: string, documentId: string, signal?: AbortSignal): Promise { @@ -1084,6 +1085,15 @@ export async function createChatSession(bankId: string, documentId: string, sign }) } +export type ChatMessageResult = Omit & { questions: ApiQuestion[] } + +export interface ChatTurnStatus { + status: 'running' | 'canceled' | 'done' | 'failed' | 'interrupted' + execution_finished: boolean + batch_id: string | null + result: ChatMessageResult | null +} + export async function sendChatMessage( sessionId: string, message: string, @@ -1092,7 +1102,8 @@ export async function sendChatMessage( images: string[] = [], mode: ChatMode = 'generate', switchOnly = false, -): Promise & { questions: ApiQuestion[] }> { + requestId?: string, +): Promise { return request(`/api/chat/sessions/${sessionId}/messages`, { method: 'POST', body: JSON.stringify({ @@ -1100,6 +1111,7 @@ export async function sendChatMessage( existing_stems: existingStems, mode, switch_only: switchOnly, + request_id: requestId, ...(images.length ? { images } : {}), }), signal, @@ -1126,8 +1138,14 @@ export async function getChatProgress( return request(`/api/chat/sessions/${sessionId}/progress`, { signal }) } -export async function cancelChat(sessionId: string): Promise { - await request<{ canceled: boolean }>(`/api/chat/sessions/${sessionId}/cancel`, { method: 'POST' }) +export async function cancelChat(sessionId: string, requestId: string, signal: AbortSignal): Promise { + return request(`/api/chat/sessions/${sessionId}/cancel?request_id=${encodeURIComponent(requestId)}`, { + method: 'POST', signal, + }) +} + +export async function getChatTurn(sessionId: string, requestId: string, signal: AbortSignal): Promise { + return request(`/api/chat/sessions/${sessionId}/requests/${encodeURIComponent(requestId)}`, { signal }) } export async function deleteChatSession(sessionId: string): Promise { diff --git a/frontend/src/components/layout/TabBar.tsx b/frontend/src/components/layout/TabBar.tsx index 5e026e5..05962bf 100644 --- a/frontend/src/components/layout/TabBar.tsx +++ b/frontend/src/components/layout/TabBar.tsx @@ -12,11 +12,11 @@ const TABS: { key: TabKey; label: string; icon: LucideIcon }[] = [ export default function TabBar() { const { - activeTab, setActiveTab, startNewChat, clearQuestions, botThinking, sessionLoading, + activeTab, setActiveTab, startNewChat, clearQuestions, botThinking, chatPauseStatus, sessionLoading, confirmBusy, pendingConfirm, generating, generationClearing, questionsClearing, generationRecoveryError, resetGenerationRecovery, retryGenerationCleanup, } = useApp() - const clearDisabled = botThinking || sessionLoading || confirmBusy || pendingConfirm !== null + const clearDisabled = botThinking || chatPauseStatus != null || sessionLoading || confirmBusy || pendingConfirm !== null || generating || generationClearing || questionsClearing || generationRecoveryError !== null const [confirmClear, setConfirmClear] = useState(false) const [confirmReset, setConfirmReset] = useState(false) diff --git a/frontend/src/components/tabs/GenerateTab/ChatInput.tsx b/frontend/src/components/tabs/GenerateTab/ChatInput.tsx index 14e304b..897f899 100644 --- a/frontend/src/components/tabs/GenerateTab/ChatInput.tsx +++ b/frontend/src/components/tabs/GenerateTab/ChatInput.tsx @@ -1,4 +1,4 @@ -import { CheckCircle2, ShieldAlert, SendHorizontal, Square, X, XCircle } from 'lucide-react' +import { CheckCircle2, LoaderCircle, ShieldAlert, SendHorizontal, Square, X, XCircle } from 'lucide-react' import { useApp } from '../../../store/AppContext' import { CHAT_MODE_LABELS } from '../../../types' import SegmentedControl from '../../ui/SegmentedControl' @@ -65,11 +65,11 @@ function ConfirmOverlay() { export default function ChatInput() { const { inputDraft, setInputDraft, sendChat, botThinking, showToast, - selectedDocId, pauseChat, chatImages, removeChatImage, + selectedDocId, pauseChat, chatPauseStatus, chatImages, removeChatImage, mode, setMode, sessionMode, modeVisible, messages, confirmBusy, pendingConfirm, sessionLoading, questionsClearing, generating, generationRecoveryError, } = useApp() - const interactionBusy = botThinking || sessionLoading || questionsClearing || generating + const interactionBusy = botThinking || chatPauseStatus != null || sessionLoading || questionsClearing || generating || generationRecoveryError !== null || confirmBusy || pendingConfirm !== null const canSend = (inputDraft.trim().length > 0 || chatImages.length > 0) && !interactionBusy @@ -139,9 +139,29 @@ export default function ChatInput() { className="block w-full resize-none bg-transparent px-1 text-sm leading-6 text-ink outline-none placeholder:text-ink-3" />
+ {chatPauseStatus === 'failed' && ( +
+ 暂停未确认 + +
+ )}
{inputDraft.length}/2000 - {botThinking ? ( + {chatPauseStatus != null ? ( + + ) : botThinking ? (
) } diff --git a/frontend/src/api/backend.ts b/frontend/src/api/backend.ts index bc4002a..f52faa2 100644 --- a/frontend/src/api/backend.ts +++ b/frontend/src/api/backend.ts @@ -986,15 +986,12 @@ export async function reviewAttempt(attemptId: string): Promise & { school?: string }): Promise { - return request('/api/users/me', { - method: 'PUT', - body: JSON.stringify({ - display_name: patch.name, - gender: patch.gender === '' ? null : patch.gender, - phone: patch.phone === '' ? null : patch.phone, - school: patch.school, - }), - }) + const body: Record = {} + if (patch.name !== undefined) body.display_name = patch.name + if (patch.gender !== undefined) body.gender = patch.gender === '' ? null : patch.gender + if (patch.phone !== undefined) body.phone = patch.phone === '' ? null : patch.phone + if (patch.school !== undefined) body.school = patch.school + return request('/api/users/me', { method: 'PUT', body: JSON.stringify(body) }) } export interface ModelSettings { @@ -1026,12 +1023,18 @@ export async function saveModelSettings(payload: { }) } -export async function testDeepSeek(): Promise { - await request('/api/users/me/model-settings/test-deepseek', { method: 'POST' }) +export async function testDeepSeek(key?: string): Promise { + await request('/api/users/me/model-settings/test-deepseek', { + method: 'POST', + body: JSON.stringify(key ? { deepseek_api_key: key } : {}), + }) } -export async function testMinerU(): Promise { - await request('/api/users/me/model-settings/test-mineru', { method: 'POST' }) +export async function testMinerU(token?: string): Promise { + await request('/api/users/me/model-settings/test-mineru', { + method: 'POST', + body: JSON.stringify(token ? { mineru_token: token } : {}), + }) } /* ---------------- 对话出题 ---------------- */ diff --git a/frontend/src/api/modelSettings.ts b/frontend/src/api/modelSettings.ts deleted file mode 100644 index 61333f0..0000000 --- a/frontend/src/api/modelSettings.ts +++ /dev/null @@ -1,3 +0,0 @@ -/** 个人模型设置统一复用带会话校验的当前用户 API。 */ -export { getModelSettings, saveModelSettings, testDeepSeek, testMinerU } from './backend' -export type { ModelSettings } from './backend' diff --git a/frontend/src/components/layout/SideNav.tsx b/frontend/src/components/layout/SideNav.tsx index f74b75f..8ebfe2a 100644 --- a/frontend/src/components/layout/SideNav.tsx +++ b/frontend/src/components/layout/SideNav.tsx @@ -1,12 +1,12 @@ import type { LucideIcon } from 'lucide-react' -import { BookOpen, Database, FileText, Home, PanelLeftClose, PanelLeftOpen, Settings, Star, User } from 'lucide-react' +import { BookOpen, Database, FileText, Home, PanelLeftClose, PanelLeftOpen, Star, User } from 'lucide-react' import { useApp } from '../../store/AppContext' const NAV_ITEMS: { key: string label: string icon: LucideIcon - tab?: 'generate' | 'bank' | 'records' | 'fav' | 'space' | 'me' | 'settings' + tab?: 'generate' | 'bank' | 'records' | 'fav' | 'space' | 'me' }[] = [ { key: 'home', label: '智能出题', icon: Home, tab: 'generate' }, { key: 'space', label: '学习空间', icon: BookOpen, tab: 'space' }, @@ -14,7 +14,6 @@ const NAV_ITEMS: { { key: 'paper', label: '组卷记录', icon: FileText, tab: 'records' }, { key: 'bank', label: '题库管理', icon: Database, tab: 'bank' }, { key: 'me', label: '个人中心', icon: User, tab: 'me' }, - { key: 'settings', label: '设置', icon: Settings, tab: 'settings' }, ] export default function SideNav() { diff --git a/frontend/src/components/settings/ModelSettings.tsx b/frontend/src/components/settings/ModelSettings.tsx deleted file mode 100644 index 05d66b0..0000000 --- a/frontend/src/components/settings/ModelSettings.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { PersonalModelSettings } from './PersonalModelSettings' - -interface ModelSettingsProps { - onDirtyChange?: (dirty: boolean) => void - onSavingChange?: (saving: boolean) => void -} - -export function ModelSettings({ onDirtyChange, onSavingChange }: ModelSettingsProps) { - return -} diff --git a/frontend/src/components/settings/PersonalModelSettings.tsx b/frontend/src/components/settings/PersonalModelSettings.tsx deleted file mode 100644 index ddc06fe..0000000 --- a/frontend/src/components/settings/PersonalModelSettings.tsx +++ /dev/null @@ -1,195 +0,0 @@ -import { Loader2 } from 'lucide-react' -import { useCallback, useEffect, useId, useRef, useState } from 'react' -import { getModelSettings, saveModelSettings, testDeepSeek, testMinerU } from '../../api/modelSettings' -import type { ModelSettings } from '../../api/modelSettings' -import { useToast } from '../../store/ToastContext' - -interface PersonalModelSettingsProps { - onDirtyChange?: (dirty: boolean) => void - onSavingChange?: (saving: boolean) => void -} - -/** 设置页个人凭据编辑;测试只验证服务端已保存的配置。 */ -export function PersonalModelSettings({ onDirtyChange, onSavingChange }: PersonalModelSettingsProps) { - const { showToast } = useToast() - const [model, setModel] = useState(null) - const [deepseekKey, setDeepseekKey] = useState('') - const [mineruToken, setMineruToken] = useState('') - const [clearDeepseek, setClearDeepseek] = useState(false) - const [clearMineru, setClearMineru] = useState(false) - const [busy, setBusy] = useState<'load' | 'save' | 'deepseek' | 'mineru' | null>('load') - const [error, setError] = useState('') - const [notice, setNotice] = useState('') - const lock = useRef(false) - const mounted = useRef(false) - const id = useId() - const dirty = deepseekKey !== '' || mineruToken !== '' || clearDeepseek || clearMineru - const disabled = busy !== null || model === null - - useEffect(() => { onDirtyChange?.(dirty) }, [dirty, onDirtyChange]) - useEffect(() => () => onDirtyChange?.(false), [onDirtyChange]) - useEffect(() => () => onSavingChange?.(false), [onSavingChange]) - useEffect(() => { - if (!dirty && busy !== 'save') return - const preventLoss = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' } - window.addEventListener('beforeunload', preventLoss) - return () => window.removeEventListener('beforeunload', preventLoss) - }, [dirty, busy]) - - const reportError = useCallback((message: string) => { - if (!mounted.current) return - setError(message) - showToast(message, 'error') - }, [showToast]) - - const reportSuccess = (message: string) => { - if (!mounted.current) return - setNotice(message) - showToast(message, 'success') - } - - const load = useCallback(async () => { - if (lock.current) return - lock.current = true - setBusy('load') - setError('') - try { - const fresh = await getModelSettings() - if (mounted.current) setModel(fresh) - } catch { - reportError('模型配置读取失败,请重试。') - } finally { - lock.current = false - if (mounted.current) setBusy(null) - } - }, [reportError]) - - useEffect(() => { - mounted.current = true - void load() - return () => { mounted.current = false } - }, [load]) - - const save = async () => { - if (lock.current || !model || !dirty) return - if ((!clearDeepseek && deepseekKey !== '' && !deepseekKey.trim()) || - (!clearMineru && mineruToken !== '' && !mineruToken.trim())) { - reportError('凭据不能仅含空格;如需删除,请勾选清除个人凭据。') - return - } - lock.current = true - setBusy('save') - onSavingChange?.(true) - setError('') - setNotice('') - try { - await saveModelSettings({ - ...(clearDeepseek ? { deepseek_api_key: '' } : deepseekKey.trim() ? { deepseek_api_key: deepseekKey.trim() } : {}), - ...(clearMineru ? { mineru_token: '' } : mineruToken.trim() ? { mineru_token: mineruToken.trim() } : {}), - }) - if (!mounted.current) return - setDeepseekKey('') - setMineruToken('') - setClearDeepseek(false) - setClearMineru(false) - // 写入已确认后,读回失败需明确提示,不能以旧状态继续测试。 - setModel(null) - try { - const fresh = await getModelSettings() - if (!mounted.current) return - setModel(fresh) - reportSuccess('模型配置已保存。现在可以测试已保存的配置。') - } catch { - reportError('保存已完成,但最新配置读取失败。请重新读取后再测试。') - } - } catch { - reportError('模型配置保存未获确认,请重试;当前输入已保留。') - } finally { - lock.current = false - onSavingChange?.(false) - if (mounted.current) setBusy(null) - } - } - - const test = async (service: 'deepseek' | 'mineru') => { - if (lock.current || !model) return - if (dirty) { - reportError('请先保存当前修改,再测试已保存的配置。') - return - } - lock.current = true - setBusy(service) - setError('') - setNotice('') - try { - if (service === 'deepseek') await testDeepSeek() - else await testMinerU() - reportSuccess(service === 'mineru' - ? 'MinerU 已保存配置鉴权通过,实际解析仍受额度和任务结果影响(含服务端默认配置)。' - : 'DeepSeek 已保存配置连接测试通过(含服务端默认配置)。') - } catch { - reportError('已保存配置测试失败,请检查凭据或服务可用性。') - } finally { - lock.current = false - if (mounted.current) setBusy(null) - } - } - - const inputClass = 'block w-full rounded-lg border border-line bg-white px-3 py-2 text-sm text-ink outline-none focus:border-primary disabled:opacity-60' - const buttonClass = 'rounded-lg border border-line px-3 py-2 text-sm text-ink-2 hover:border-primary disabled:opacity-50' - const edit = (change: () => void) => { change(); setNotice(''); setError('') } - - return
-
-

个人模型配置

- -
-

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

- {busy === 'load' &&

正在读取配置…

} - {error &&

{error}

} - {notice &&

{notice}

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

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

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

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

- -
-
- MinerU OCR -

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

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

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

- {model &&

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

} -

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

- -
- {dirty &&

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

} - {model &&
-

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

-

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

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

模型与服务

-

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

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

{hint}

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

+ + API 配置 +

+ {loading ? ( +

+ + 正在读取配置… +

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

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

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

+ + 需要配置 API Key +

+ +
+
+

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

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

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

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

账号 ID:{profile.teacherId}

-
- -
-

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

-

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

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

- - 基本信息 -

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

{profileError}

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

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

- - -
-

- + {/* 安全管理:按钮靠左 */} +
+

+ + 安全管理 +

+ {pwdError &&

{pwdError}

} +
+

-
-
-

修改密码

-

修改后需要重新登录

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

修改密码

+

+ + 修改密码 +

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

+ + 联系管理员 +

+ +
+
+

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

+
+
+ +
+
+
+ )}
) } diff --git a/frontend/src/store/AppContext.tsx b/frontend/src/store/AppContext.tsx index b933499..0fedbaa 100644 --- a/frontend/src/store/AppContext.tsx +++ b/frontend/src/store/AppContext.tsx @@ -31,7 +31,7 @@ import type { AuthRole, AuthUser } from '../api/auth' const isChatMode = (value: string): value is ChatMode => value in CHAT_MODE_LABELS const QUESTION_DELETE_BATCH_SIZE = 200 -export type TabKey = 'generate' | 'preview' | 'bank' | 'records' | 'fav' | 'space' | 'me' | 'settings' +export type TabKey = 'generate' | 'preview' | 'bank' | 'records' | 'fav' | 'space' | 'me' /** 历史会话侧边栏列表项(来自后端,按账号隔离) */ export interface ChatSessionSummary { @@ -50,7 +50,7 @@ function buildProfile(user: AuthUser | null): TeacherProfile { gender: user?.gender === '男' || user?.gender === '女' ? user.gender : '', phone: user?.phone ?? '', email: user?.email ?? '', - teacherId: user?.userNo ?? '', + teacherId: user?.username ?? '', school: user?.school ?? '', identity: user?.identity ?? '', } @@ -86,11 +86,12 @@ interface AppState { /** 删除受理后立即清理选中项与缓存,阻止旧请求重新写入。 */ invalidateDocument: (bankId: string, documentId: string) => void - /** 个人模型设置页的未保存提醒 */ - hasUnsavedChanges: boolean - setHasUnsavedChanges: (v: boolean) => void - isSettingsSaving: boolean - setIsSettingsSaving: (saving: boolean) => void + /** 个人 API 配置(脱敏);未配置 DeepSeek Key 时出题被拦截 */ + modelSettings: api.ModelSettings | null + refreshModelSettings: () => Promise + /** 未配置 API 时的引导弹窗 */ + apiConfigOpen: boolean + closeApiConfigModal: () => void generationRecoveryError: string | null resetGenerationRecovery: () => void @@ -278,19 +279,11 @@ export function AppProvider({ children }: { children: ReactNode }) { const [bankNotifUnread, setBankNotifUnread] = useState(0) const [bankNotifItems, setBankNotifItems] = useState([]) const [pendingSpacePaper, setPendingSpacePaper] = useState<{ spaceId: string; paperId: string } | null>(null) - // 个人模型设置页的未保存提醒 - const [hasUnsavedChanges, setHasUnsavedChangesState] = useState(false) - const [isSettingsSaving, setIsSettingsSavingState] = useState(false) - const settingsDirtyRef = useRef(false) - const settingsSavingRef = useRef(false) - const setHasUnsavedChanges = useCallback((dirty: boolean) => { - settingsDirtyRef.current = dirty - setHasUnsavedChangesState(dirty) - }, []) - const setIsSettingsSaving = useCallback((saving: boolean) => { - settingsSavingRef.current = saving - setIsSettingsSavingState(saving) - }, []) + // 个人 API 配置:登录后读取一次;未配置 DeepSeek Key 时弹出引导并拦截出题 + const [modelSettings, setModelSettings] = useState(null) + const [apiConfigOpen, setApiConfigOpen] = useState(false) + const apiConfigPromptedRef = useRef(false) + const activeBatchRef = useRef(null) const chatSessionRef = useRef<{ id: string; bankId: string; docId: string } | null>(null) const chatAbortRef = useRef(null) @@ -323,6 +316,18 @@ export function AppProvider({ children }: { children: ReactNode }) { [], ) + const refreshModelSettings = useCallback(async () => { + const fresh = await api.getModelSettings() + if (!sessionIsCurrent()) return + setModelSettings(fresh) + const missing = !fresh.deepseek_key_configured || !fresh.mineru_token_configured + if (missing && !apiConfigPromptedRef.current) { + apiConfigPromptedRef.current = true + setApiConfigOpen(true) + } + }, [sessionIsCurrent]) + const closeApiConfigModal = useCallback(() => setApiConfigOpen(false), []) + useEffect(() => { mounted.current = true return () => { @@ -353,15 +358,10 @@ export function AppProvider({ children }: { children: ReactNode }) { const setActiveTab = useCallback((tab: TabKey): boolean => { if (tab === activeTabRef.current) return true - if (settingsSavingRef.current) { - showToast('配置正在保存,请等待完成后再离开', 'error') - return false - } - if (settingsDirtyRef.current && !window.confirm('有未保存的模型配置,离开将丢弃修改。确定离开吗?')) return false activeTabRef.current = tab setActiveTabState(tab) return true - }, [showToast]) + }, []) // 同步失效会话回调,防止清空、切库或切文档后的旧结果回填。 const resetChat = useCallback(() => { @@ -665,6 +665,11 @@ export function AppProvider({ children }: { children: ReactNode }) { })() }, [user, loadFavorites, loadRecords, loadSessions, refreshSpaces, sessionIsCurrent, showToast, isClearing]) + useEffect(() => { + if (!user) return + void refreshModelSettings().catch(() => undefined) + }, [user, refreshModelSettings]) + const selectKb = useCallback( (id: string) => { if (!sessionIsCurrent()) return @@ -736,6 +741,11 @@ export function AppProvider({ children }: { children: ReactNode }) { showToast('请先在右侧选择知识库文档,才能基于知识库出题') return } + if (modelSettings && !modelSettings.deepseek_key_configured) { + apiConfigPromptedRef.current = true + setApiConfigOpen(true) + return + } const effectiveMode = opts?.mode ?? mode const version = chatVersionRef.current const previewVersion = ++previewVersionRef.current @@ -825,7 +835,7 @@ export function AppProvider({ children }: { children: ReactNode }) { } }, [mode, loadSessions, selectedDocId, selectedKbId, questions, generating, generationRecoveryError, - sessionIsCurrent, setPendingConfirm, showToast], + sessionIsCurrent, setPendingConfirm, showToast, modelSettings], ) const addChatImages = useCallback((files: File[]) => { @@ -1578,10 +1588,10 @@ export function AppProvider({ children }: { children: ReactNode }) { selectDoc, refreshKbs, invalidateDocument, - hasUnsavedChanges, - setHasUnsavedChanges, - isSettingsSaving, - setIsSettingsSaving, + modelSettings, + refreshModelSettings, + apiConfigOpen, + closeApiConfigModal, generating, generationClearing, generationRecoveryError, diff --git a/openapi.json b/openapi.json index 354e7c9..6a80317 100644 --- a/openapi.json +++ b/openapi.json @@ -2090,7 +2090,7 @@ "users" ], "summary": "Test Deepseek", - "description": "测试 DeepSeek 连接,失败仅返回固定脱敏提示。", + "description": "测试 DeepSeek 连接;body 提供输入值时优先测试该值,不落库。失败仅返回固定脱敏提示。", "operationId": "test_deepseek_api_users_me_model_settings_test_deepseek_post", "parameters": [ { @@ -2110,6 +2110,23 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModelTestBody" + }, + { + "type": "null" + } + ], + "title": "Body" + } + } + } + }, "responses": { "200": { "description": "Successful Response", @@ -2138,7 +2155,7 @@ "users" ], "summary": "测试 MinerU 连接与鉴权(不验证文件解析)", - "description": "只读验证已保存 MinerU 配置的连接与鉴权,不验证额度或实际文件解析。\n\n严格校验 HTTP、JSON 与业务状态,仅将明确成功或官方找不到探测任务视为通过。", + "description": "只读验证 MinerU 配置的连接与鉴权;body 提供输入值时优先测试该值,不落库。\n\n严格校验 HTTP、JSON 与业务状态,仅将明确成功或官方找不到探测任务视为通过。", "operationId": "test_mineru_api_users_me_model_settings_test_mineru_post", "parameters": [ { @@ -2158,6 +2175,23 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModelTestBody" + }, + { + "type": "null" + } + ], + "title": "Body" + } + } + } + }, "responses": { "200": { "description": "Successful Response", @@ -9858,6 +9892,37 @@ "type": "object", "title": "ModelSettingsBody" }, + "ModelTestBody": { + "properties": { + "deepseek_api_key": { + "anyOf": [ + { + "type": "string", + "maxLength": 128 + }, + { + "type": "null" + } + ], + "title": "Deepseek Api Key" + }, + "mineru_token": { + "anyOf": [ + { + "type": "string", + "maxLength": 128 + }, + { + "type": "null" + } + ], + "title": "Mineru Token" + } + }, + "type": "object", + "title": "ModelTestBody", + "description": "连接测试的可选输入值;提供时优先测试该值,不落库。" + }, "NotificationReadBody": { "properties": { "ids": { From f0fc56abc33c0de1fbe1f36a8ea25b9809066be2 Mon Sep 17 00:00:00 2001 From: LBL <906158807@qq.com> Date: Thu, 19 Nov 2026 17:26:37 +0800 Subject: [PATCH 3/8] =?UTF-8?q?feat(generate):=20=E8=81=8A=E5=A4=A9?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E6=93=8D=E4=BD=9C=E6=94=B9=E4=B8=BA=E5=A4=8D?= =?UTF-8?q?=E5=88=B6=E4=B8=8E=E7=BC=96=E8=BE=91=E9=87=8D=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 仅最新一条用户消息保留复制与编辑重发按钮,历史消息仅可复制, 移除回退并重新发送按钮,避免误触回退丢失后续上下文。 --- .../src/components/tabs/GenerateTab/index.tsx | 41 ++++++++----------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/frontend/src/components/tabs/GenerateTab/index.tsx b/frontend/src/components/tabs/GenerateTab/index.tsx index 140f17c..047660f 100644 --- a/frontend/src/components/tabs/GenerateTab/index.tsx +++ b/frontend/src/components/tabs/GenerateTab/index.tsx @@ -38,8 +38,9 @@ export default function GenerateTab() { if (docs.length) void uploadDocument(docs[0]) } - // 用户消息沿用历史编辑、回退重发入口;最新 AI 回复保留重新生成。 + // 用户消息:最新一条有复制、编辑后重发;历史消息只保留复制。AI 回复最新一条保留重新生成。 const lastAssistantIndex = messages.reduce((acc, m, i) => (m.role === 'assistant' ? i : acc), -1) + const lastUserIndex = messages.reduce((acc, m, i) => (m.role === 'user' ? i : acc), -1) const regenerateFrom = (assistantIndex: number) => { if (interactionBusy) return for (let j = assistantIndex - 1; j >= 0; j--) { @@ -129,30 +130,20 @@ export default function GenerateTab() { > - - + {i === lastUserIndex && ( + + )}
)} {m.role === 'assistant' && ( From 4cd0aaca6ae2e5988bd59a88335322f869c88488 Mon Sep 17 00:00:00 2001 From: LBL <906158807@qq.com> Date: Thu, 19 Nov 2026 17:26:41 +0800 Subject: [PATCH 4/8] =?UTF-8?q?refactor(banks):=20=E9=A2=98=E5=BA=93?= =?UTF-8?q?=E4=B8=8E=E5=AD=A6=E4=B9=A0=E7=A9=BA=E9=97=B4=E7=BC=96=E5=8F=B7?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=2010=20=E4=BD=8D=E9=9A=8F=E6=9C=BA=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 编号由前缀加长串十六进制改为前缀加 8 位随机字符,避免从编号 推断创建顺序与规模,也便于口头传达;同步更新加入码格式断言 与模型字段注释。 --- backend/app/models/bank.py | 2 +- backend/app/models/space.py | 2 +- backend/app/services/banks.py | 14 ++++++-------- backend/app/services/spaces.py | 7 +++++-- backend/tests/test_account_resource_regressions.py | 2 +- 5 files changed, 14 insertions(+), 13 deletions(-) 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/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/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/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"] From b1677673918187b79c3e18c8d35791110031d354 Mon Sep 17 00:00:00 2001 From: LBL <906158807@qq.com> Date: Thu, 19 Nov 2026 17:27:38 +0800 Subject: [PATCH 5/8] =?UTF-8?q?feat(rag):=20=E5=BF=AB=E9=80=9F=E5=87=BA?= =?UTF-8?q?=E9=A2=98=E6=94=B9=E7=94=A8=E6=A8=A1=E5=9E=8B=E6=8A=BD=E5=8F=96?= =?UTF-8?q?=E6=A7=BD=E4=BD=8D=E5=B9=B6=E6=94=AF=E6=8C=81=E9=A2=98=E5=9E=8B?= =?UTF-8?q?=E7=BA=A7=E9=9A=BE=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 抽取模板覆盖知识点范围、题型、数量与题型级难度,同义词先归一, 未提及字段一律留空禁止猜测;同一题型给出多个难度档时按混合 难度保留原始描述,多轮对话沿用已确认的难度不再压缩成单档。 缺槽时由模型生成自然追问,失败或未配置密钥时回退固定模板。 题型级难度贯通命题提示词、考点规划、题目标注与盲评目标档, 补齐与换模板重出携带对应难度;/api/generate 请求契约新增 题型级 difficulty 并重新生成接口文档。 --- backend/app/schemas/api.py | 2 + backend/app/schemas/question.py | 2 + backend/app/services/generation.py | 8 +- backend/app/services/question_review.py | 9 +- backend/app/services/rag/chat_flow.py | 19 +- backend/app/services/rag/prompts.py | 54 ++++-- backend/app/services/rag/question_gen.py | 21 ++- backend/app/services/rag/slots.py | 167 +++++++++++++++--- backend/tests/test_chat_requirements.py | 75 ++++++++ ...41\346\201\257\346\243\200\346\237\245.md" | 24 +-- openapi.json | 12 ++ 11 files changed, 333 insertions(+), 60 deletions(-) diff --git a/backend/app/schemas/api.py b/backend/app/schemas/api.py index 0a6b761..f78c87d 100644 --- a/backend/app/schemas/api.py +++ b/backend/app/schemas/api.py @@ -14,6 +14,8 @@ 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): 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/generation.py b/backend/app/services/generation.py index fd2471f..83962eb 100644 --- a/backend/app/services/generation.py +++ b/backend/app/services/generation.py @@ -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, 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/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/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/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/openapi.json b/openapi.json index 6a80317..228d8b8 100644 --- a/openapi.json +++ b/openapi.json @@ -11835,6 +11835,18 @@ "maximum": 100.0, "minimum": 1.0, "title": "Count" + }, + "difficulty": { + "anyOf": [ + { + "type": "string", + "pattern": "^(低|中|高|地狱)$" + }, + { + "type": "null" + } + ], + "title": "Difficulty" } }, "type": "object", From 494582671ec74ea1100285bafa728bbd9a15e7d6 Mon Sep 17 00:00:00 2001 From: LBL <906158807@qq.com> Date: Thu, 19 Nov 2026 18:24:30 +0800 Subject: [PATCH 6/8] =?UTF-8?q?fix(profile):=20=E6=81=A2=E5=A4=8D=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E5=AE=89=E5=85=A8=E8=B5=84=E6=96=99=E5=85=A5=E5=8F=A3?= =?UTF-8?q?=E5=B9=B6=E5=AF=B9=E9=BD=90=E5=9B=9E=E5=BD=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 个人中心重构时遗漏了 SecuritySettings 渲染,学工号资料与邮箱绑定、 换绑、解绑在界面上不可达;重新挂载该组件并补回登录账号与邮箱展示 行,修改密码与联系管理员入口保留在账号安全区内。回归脚本同步更新: merge-frontend 的设置页用例改为覆盖 API 配置卡的测试不落库、保存 读回掩码、眼睛回显本机密钥与清空行为;假服务默认 DeepSeek 已配置, 与发送拦截的新行为一致;e2e-auth 的模型配置假响应补齐就绪字段。 --- frontend/e2e-auth.mjs | 2 +- frontend/merge-frontend-regression.mjs | 100 ++++++++++-------- .../src/components/tabs/ProfileTab/index.tsx | 74 +++++++------ 3 files changed, 96 insertions(+), 80 deletions(-) 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..8f86335 100644 --- a/frontend/merge-frontend-regression.mjs +++ b/frontend/merge-frontend-regression.mjs @@ -38,7 +38,7 @@ const bundle = await build({ import {ApiError} from './src/api/backend'; import {ToastProvider} from './src/store/ToastContext'; import Toast from './src/components/ui/Toast'; - import {SettingsPage} from './src/components/settings/SettingsPage'; + import {ApiConfigCard} from './src/components/tabs/ProfileTab/ApiConfigCard'; import BankCreateModal from './src/components/tabs/BankTab/BankCreateModal'; import BankEditModal from './src/components/tabs/BankTab/BankEditModal'; import BankViewModal from './src/components/tabs/BankTab/BankViewModal'; @@ -77,11 +77,7 @@ const bundle = await build({ {h.mode === 'history' && } - {h.mode === 'settings' && <> - - - {app.activeTab === 'settings' && } - } + {h.mode === 'settings' && } {h.mode === 'create' && } {h.mode === 'edit' && } {h.mode === 'view' && } @@ -165,10 +161,11 @@ async function mount(mode, role = 'teacher', memberRole = 'creator', format = 'T listChatSessions: () => h.sessions ?? [], getChatSession: id => ({session_id:id, mode:'generate', messages:[]}), listQuestions: () => ({items:[]}), listBanks: () => h.banks ?? [h.apiBank], latestBatch: () => ({batch_id:null, questions:[]}), - getModelSettings: () => ({deepseek_model:'fake-deepseek', deepseek_key_configured:false, - deepseek_key_masked:null, mineru_token_configured:false, mineru_token_masked:null, + getModelSettings: () => ({deepseek_model:'fake-deepseek', deepseek_key_configured:true, + deepseek_key_masked:'sk-****kOJl', mineru_token_configured:false, mineru_token_masked:null, mineru_limits:{max_file_mb:100, max_pages:200}, embedding_model:'fake-embedding', rerank_model:'fake-rerank'}), saveModelSettings: () => {}, + testDeepSeek: () => {}, testMinerU: () => {}, listFavoriteGroups: () => [], listFavorites: () => h.favoriteRows, listPapers: () => h.paperRows, listSpaces: () => [], getPaperApi: id => h.paperRows.find(paper => paper.id === id), mapPaper: paper => paper, @@ -255,55 +252,64 @@ async function prepareConfirmation(page, entity, action = 'delete') { { if (!(process.argv.includes('--chat-only') || process.argv.includes('--generation-only'))) { const settings = await mount('settings') - await settings.getByRole('button', {name:'打开个人设置', exact:true}).click() - const key = settings.getByLabel('新的 DeepSeek API Key', {exact:true}) + const key = settings.getByLabel('请输入您的校内 DeepSeek Key', {exact:true}) + await settings.getByText('校内 DeepSeek Key', {exact:true}).waitFor() + // DeepSeek 已配置:browse 态展示服务端掩码;MinerU 未配置时测试与保存不可用 + assert.equal(await key.inputValue(), 'sk-****kOJl') + assert.equal(await settings.getByRole('button', {name:'测试', exact:true}).last().isDisabled(), true) + assert.equal(await settings.getByRole('button', {name:'保存', exact:true}).last().isDisabled(), true) + // 本机没有保存过完整 Key 时,眼睛提示需要重新输入 + await settings.getByRole('button', {name:'显示完整 Key', exact:true}).first().click() + await settings.getByText('完整 Key 仅保存在配置它的这台电脑上').first().waitFor() + // 测试当前输入的 Key 不落库 + await key.click() await key.fill('synthetic-draft-key') - await settings.waitForFunction(() => window.mergeApp.hasUnsavedChanges) - const leaveSettings = settings.getByRole('button', {name:'离开个人设置', exact:true}) - let dialog = settings.waitForEvent('dialog') - let click = leaveSettings.click() - await (await dialog).dismiss() - await click - assert.equal(await key.inputValue(), 'synthetic-draft-key') - assert.equal(await settings.evaluate(() => !window.dispatchEvent(new Event('beforeunload', {cancelable:true}))), true) - dialog = settings.waitForEvent('dialog') - click = leaveSettings.click() - await (await dialog).accept() - await click - await settings.waitForFunction(() => window.mergeApp.activeTab === 'preview' && !window.mergeApp.hasUnsavedChanges) - await settings.getByRole('button', {name:'打开个人设置', exact:true}).click() - await key.waitFor() - assert.equal(await key.inputValue(), '') - await key.fill('synthetic-saved-key') + const testButton = settings.getByRole('button', {name:'测试', exact:true}).first() + assert.equal(await testButton.isDisabled(), false) + await settings.evaluate(() => { window.mergeHarness.held.testDeepSeek = true }) + await testButton.click() + await settings.waitForFunction(() => window.mergeHarness.pending.testDeepSeek?.length === 1) + assert.equal(await settings.evaluate(() => window.mergeHarness.calls.some(call => call.name === 'saveModelSettings')), false) + await settings.evaluate(() => window.mergeHarness.finish('testDeepSeek')) + await settings.getByText('校内 DeepSeek 连接成功').first().waitFor() + // 保存携带草稿值并读回新掩码 await settings.evaluate(() => { window.mergeHarness.held.saveModelSettings = true }) - await settings.getByRole('button', {name:'保存配置', exact:true}).click() + await settings.getByRole('button', {name:'保存', exact:true}).first().click() await settings.waitForFunction(() => window.mergeHarness.pending.saveModelSettings?.length === 1) - await leaveSettings.click() - assert.equal(await settings.evaluate(() => window.mergeApp.activeTab), 'settings') - assert.equal(await settings.evaluate(() => window.mergeApp.isSettingsSaving), true) - await settings.getByRole('alert').filter({hasText:'配置正在保存,请等待完成后再离开'}).waitFor() + assert.deepEqual(await settings.evaluate(() => window.mergeHarness.pending.saveModelSettings[0].args[0]), + {deepseek_api_key:'synthetic-draft-key'}) await settings.evaluate(() => { - const h = window.mergeHarness; h.held.getModelSettings = true; h.finish('saveModelSettings'); + const h = window.mergeHarness + h.held.getModelSettings = true + h.finish('saveModelSettings') }) await settings.waitForFunction(() => window.mergeHarness.pending.getModelSettings?.length === 1) - await settings.waitForFunction(input => input.value === '', await key.elementHandle()) - assert.equal(await key.inputValue(), '') - assert.equal(await settings.evaluate(() => !window.dispatchEvent(new Event('beforeunload', {cancelable:true}))), true) - await leaveSettings.click() - assert.equal(await settings.evaluate(() => window.mergeApp.activeTab), 'settings') await settings.evaluate(() => { - const h = window.mergeHarness; h.held.getModelSettings = false; + const h = window.mergeHarness + h.held.getModelSettings = false h.finish('getModelSettings', {deepseek_model:'fake-deepseek', deepseek_key_configured:true, - deepseek_key_masked:'***', mineru_token_configured:false, mineru_token_masked:null, - mineru_limits:{max_file_mb:100, max_pages:200}, embedding_model:'fake-embedding', rerank_model:'fake-rerank'}); + deepseek_key_masked:'sk-****yZ8w', mineru_token_configured:false, mineru_token_masked:null, + mineru_limits:{max_file_mb:100, max_pages:200}, embedding_model:'fake-embedding', rerank_model:'fake-rerank'}) }) - await settings.getByRole('status').filter({hasText:'模型配置已保存。现在可以测试已保存的配置。'}).last().waitFor() - await settings.waitForFunction(() => !window.mergeApp.isSettingsSaving && !window.mergeApp.hasUnsavedChanges) - assert.equal(await settings.evaluate(() => !window.dispatchEvent(new Event('beforeunload', {cancelable:true}))), false) - await leaveSettings.click() - await settings.waitForFunction(() => window.mergeApp.activeTab === 'preview') + await settings.getByText('校内 DeepSeek Key 已保存').first().waitFor() + await settings.waitForFunction(() => + document.querySelector('input[aria-label="请输入您的校内 DeepSeek Key"]').value === 'sk-****yZ8w') + // 完整 Key 只写入本机浏览器,供眼睛图标回显 + assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem('mathcraft-personal-keys'))), + {A:{deepseek:'synthetic-draft-key'}}) + await settings.getByRole('button', {name:'显示完整 Key', exact:true}).first().click() + await settings.waitForFunction(() => + document.querySelector('input[aria-label="请输入您的校内 DeepSeek Key"]').value === 'synthetic-draft-key') + await settings.getByRole('button', {name:'显示掩码', exact:true}).first().click() + await settings.waitForFunction(() => + document.querySelector('input[aria-label="请输入您的校内 DeepSeek Key"]').value === 'sk-****yZ8w') + // 清空草稿后保持编辑态,不回填掩码 + await key.click() + await key.fill('new-draft') + await settings.getByRole('button', {name:'清空校内 DeepSeek Key输入', exact:true}).click() + assert.equal(await key.inputValue(), '') await settings.close() - pass('personal settings keep cancelled drafts, confirm discard, block navigation and refresh throughout save/readback, retain real Toast feedback') + pass('api config card tests unsaved key without persisting, saves and reads back masked value, eye reveals local full key, clear keeps edit mode') const student = await mount('create', 'student') assert.equal(await student.getByRole('heading', {name:'新建题库', exact:true}).count(), 0) diff --git a/frontend/src/components/tabs/ProfileTab/index.tsx b/frontend/src/components/tabs/ProfileTab/index.tsx index cb46054..4502ee8 100644 --- a/frontend/src/components/tabs/ProfileTab/index.tsx +++ b/frontend/src/components/tabs/ProfileTab/index.tsx @@ -14,6 +14,7 @@ import { import { useApp } from '../../../store/AppContext' import { ApiConfigCard } from './ApiConfigCard' +import { SecuritySettings } from './SecuritySettings' import { changePasswordCurrent, validateNewPassword, getAuthConfig } from '../../../api/auth' import type { AuthConfig } from '../../../api/auth' import { useAuth } from '../../../store/AuthContext' @@ -21,7 +22,7 @@ import { getSessionGeneration } from '../../../api/session' export default function ProfileTab() { const { profile, updateProfile, showToast } = useApp() - const { setAuthNotice } = useAuth() + const { user, setAuthNotice } = useAuth() const session = useRef(getSessionGeneration()) const [pwdError, setPwdError] = useState('') @@ -173,41 +174,50 @@ export default function ProfileTab() { 身份:{profile.identity}
+
+ 登录账号 + {profile.teacherId} + + 邮箱(可选) + + {user?.email + ? `${user.email}(${user.emailVerified ? '已验证' : '待验证'},在下方账号安全管理)` + : '未绑定,可在下方账号安全中绑定'} + +
- {/* 安全管理:按钮靠左 */} -
-

- - 安全管理 -

- {pwdError &&

{pwdError}

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

{pwdError}

} +
+ + +
-
+ {/* API 配置 */} From dbfc51e9acdbc5756ddfcabfeb9b271e09e0d3dc Mon Sep 17 00:00:00 2001 From: LBL <906158807@qq.com> Date: Thu, 19 Nov 2026 18:38:17 +0800 Subject: [PATCH 7/8] =?UTF-8?q?fix(lint):=20=E8=A1=A5=E5=85=A8=E5=9B=9E?= =?UTF-8?q?=E5=BD=92=E8=84=9A=E6=9C=AC=E5=85=A8=E5=B1=80=E5=A3=B0=E6=98=8E?= =?UTF-8?q?=E5=B9=B6=E7=A7=BB=E9=99=A4=E6=9C=AA=E7=94=A8=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 设置页用例改写后直接访问 document 与 localStorage,需加入脚本顶部 的 global 白名单;beforeunload 场景移除后 Event 不再使用。 --- frontend/merge-frontend-regression.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/merge-frontend-regression.mjs b/frontend/merge-frontend-regression.mjs index 8f86335..93b16a1 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, document, localStorage, process, window, File, Response, AbortSignal */ /** 主线整合风险回归:真实 React/题库适配层,内存假服务,浏览器所有网络均阻断。 */ import assert from 'node:assert/strict' import { runChatHistoryCases, runGenerationTaskCases } from './merge-session-cases.mjs' From 3b0ef57317976a9a84b6b140476cf5d344a184c9 Mon Sep 17 00:00:00 2001 From: Logic <241731638@m.gduf.edu.cn> Date: Thu, 19 Nov 2026 20:37:20 +0800 Subject: [PATCH 8/8] =?UTF-8?q?ci(frontend):=20=E4=BD=BF=E7=94=A8=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E5=99=A8=E9=A2=84=E8=A3=85=E7=9A=84=E6=B5=8F=E8=A7=88?= =?UTF-8?q?=E5=99=A8=E7=B3=BB=E7=BB=9F=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ubuntu 软件源连续两次返回 503,阻塞前端检查。CI 使用镜像预装的系统库,直接安装锁定 Playwright 版本配套的 Chromium,并继续运行全部前端回归。 --- .github/workflows/checks.yml | 4 ++-- frontend/README.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) 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/frontend/README.md b/frontend/README.md index 9366c06..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 检查和一次生产构建,再按以下固定顺序逐个运行脚本: