DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(chat): regenerate last response (CLI, WebSocket, Web UI) (#349)
Roman Barlos0f6c81b7329f
diff --git a/AGENTS.md b/AGENTS.mdindex 599f9ac13..6b2091678 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -68,6 +68,7 @@ deeptutor run deep_question "Linear algebra" --config num_questions=5# Interactive REPLdeeptutor chat+# (inside the REPL: /regenerate or /retry re-runs the last user message)# Knowledge basesdeeptutor kb listdiff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex 75c0ba72c..a3868d796 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -456,7 +456,49 @@ class AgenticChatPipeline:{"trace_kind": "call_status", "call_state": "complete"},),)- return clean_thinking_tags("".join(chunks), self.binding, self.model), trace_meta+ final_response = clean_thinking_tags("".join(chunks), self.binding, self.model)+ if not final_response.strip():+ # The provider returned an empty stream (zero non-empty chunks)+ # or only whitespace. This typically means: model hit a token+ # limit, was filtered, or treated the observation as the final+ # answer. Surface a non-terminal warning so the operator sees+ # the cause in logs and the UI can hint a Regenerate.+ prompt_chars = sum(len(str(m.get("content") or "")) for m in messages)+ logger.warning(+ "[%s] responding stage returned empty response "+ "(model=%s, chunks=%d, prompt_chars=%d, max_tokens=%d, observation_chars=%d)",+ trace_meta.get("call_id"),+ self.model,+ len(chunks),+ prompt_chars,+ self._chat_limits.responding,+ len(observation or ""),+ )+ await stream.error(+ self._t(+ "notices.empty_response",+ default=(+ "The model returned an empty response. "+ "Try Regenerate or rephrase the question."+ ),+ ),+ source="chat",+ stage="responding",+ metadata=merge_trace_metadata(+ trace_meta,+ {+ "trace_kind": "warning",+ "warning_kind": "empty_response",+ "chunks": len(chunks),+ "prompt_chars": prompt_chars,+ "max_tokens": self._chat_limits.responding,+ # Explicitly mark as non-terminal so the runtime+ # does not flip the turn to ``failed``.+ "turn_terminal": False,+ },+ ),+ )+ return final_response, trace_metaasync def _stage_answer_now(self,diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.pyindex e514a26af..4de9e1e02 100644--- a/deeptutor/api/routers/unified_ws.py+++ b/deeptutor/api/routers/unified_ws.py@@ -3,6 +3,22 @@ Unified WebSocket Endpoint==========================Single ``/api/v1/ws`` endpoint for turn-based execution and replayable streaming.++Supported client message ``type`` values:++- ``message`` / ``start_turn`` — start a new turn from a payload.+- ``subscribe_turn`` — stream events of an existing turn (with ``after_seq``).+- ``subscribe_session`` — stream events of the active turn for a session.+- ``resume_from`` — resume an in-flight turn after reconnection.+- ``unsubscribe`` — stop a previously created subscription.+- ``cancel_turn`` — cancel a running turn.+- ``regenerate`` — re-run the last user message in the given session as a+ brand-new turn. Replaces the trailing assistant message (if any) and+ reuses the session's stored capability/tools/preferences. Optional+ ``overrides`` field accepts ``capability``, ``tools``, ``knowledge_bases``,+ ``language``, ``config``, ``notebook_references``, ``history_references``.+ Errors: ``regenerate_busy`` (another turn is running) and+ ``nothing_to_regenerate`` (no prior user message)."""from __future__ import annotations@@ -146,6 +162,41 @@ async def unified_websocket(ws: WebSocket) -> None:await safe_send({"type": "error", "content": f"Turn not found: {turn_id}"})continue+ if msg_type == "regenerate":+ session_id = str(msg.get("session_id") or "").strip()+ if not session_id:+ await safe_send({"type": "error", "content": "Missing session_id."})+ continue+ from deeptutor.services.session import get_turn_runtime_manager++ runtime = get_turn_runtime_manager()+ overrides = msg.get("overrides") if isinstance(msg.get("overrides"), dict) else None+ try:+ _, turn = await runtime.regenerate_last_turn(+ session_id,+ overrides=overrides,+ )+ except RuntimeError as exc:+ await safe_send(+ {+ "type": "error",+ "source": "unified_ws",+ "stage": "",+ "content": str(exc),+ "metadata": {+ "turn_terminal": True,+ "status": "rejected",+ "reason": str(exc),+ },+ "session_id": session_id,+ "turn_id": "",+ "seq": 0,+ }+ )+ continue+ await subscribe_turn(turn["id"], after_seq=0)+ continue+await safe_send({"type": "error", "content": f"Unknown type: {msg_type}"})except WebSocketDisconnect:diff --git a/deeptutor/app/facade.py b/deeptutor/app/facade.pyindex b5539ad20..4d5ae10ff 100644--- a/deeptutor/app/facade.py+++ b/deeptutor/app/facade.py@@ -136,6 +136,13 @@ class DeepTutorApp:async def cancel_turn(self, turn_id: str) -> bool:return await self.runtime.cancel_turn(turn_id)+ async def regenerate_last_turn(+ self,+ session_id: str,+ overrides: dict[str, Any] | None = None,+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ return await self.runtime.regenerate_last_turn(session_id, overrides=overrides)+async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:return await self.store.list_sessions(limit=limit, offset=offset)diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex eae63e343..bd71f8be5 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -597,6 +597,50 @@ class SQLiteSessionStore:attachments,)+ def _delete_message_sync(self, message_id: int) -> bool:+ with self._connect() as conn:+ cur = conn.execute("DELETE FROM messages WHERE id = ?", (int(message_id),))+ conn.commit()+ return cur.rowcount > 0++ async def delete_message(self, message_id: int) -> bool:+ return await self._run(self._delete_message_sync, message_id)++ def _get_last_message_sync(+ self, session_id: str, role: str | None = None+ ) -> dict[str, Any] | None:+ with self._connect() as conn:+ if role is None:+ row = conn.execute(+ """+ SELECT id, session_id, role, content, capability, events_json, attachments_json, created_at+ FROM messages+ WHERE session_id = ?+ ORDER BY id DESC+ LIMIT 1+ """,+ (session_id,),+ ).fetchone()+ else:+ row = conn.execute(+ """+ SELECT id, session_id, role, content, capability, events_json, attachments_json, created_at+ FROM messages+ WHERE session_id = ? AND role = ?+ ORDER BY id DESC+ LIMIT 1+ """,+ (session_id, role),+ ).fetchone()+ if row is None:+ return None+ return self._serialize_message(row)++ async def get_last_message(+ self, session_id: str, role: str | None = None+ ) -> dict[str, Any] | None:+ return await self._run(self._get_last_message_sync, session_id, role)+def _serialize_message(self, row: sqlite3.Row) -> dict[str, Any]:return {"id": row["id"],diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex a63a425a4..7dbd3f7c2 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -154,6 +154,17 @@ def _extract_persist_user_message(config: dict[str, Any] | None) -> bool:return bool(raw)+def _extract_regenerate_flag(config: dict[str, Any] | None) -> bool:+ if not isinstance(config, dict):+ return False+ raw = config.pop("_regenerate", False)+ if isinstance(raw, bool):+ return raw+ if isinstance(raw, str):+ return raw.strip().lower() in {"true", "1", "yes"}+ return bool(raw)++def _format_followup_question_context(context: dict[str, Any], language: str = "en") -> str:options = context.get("options") or {}option_lines = []@@ -276,6 +287,9 @@ class TurnRuntimeManager:raw_config = dict(payload.get("config", {}) or {})runtime_only_keys = ("_persist_user_message",+ "_regenerate",+ "_regenerated_from_message_id",+ "_superseded_turn_id","followup_question_context","answer_now_context",)@@ -312,12 +326,24 @@ class TurnRuntimeManager:capability=capability,payload=dict(payload),)+ session_metadata: dict[str, Any] = {+ "session_id": session["id"],+ "turn_id": turn["id"],+ }+ regenerated_from = runtime_only_config.get("_regenerated_from_message_id")+ if regenerated_from is not None:+ session_metadata["regenerated_from_message_id"] = regenerated_from+ superseded_turn_id = runtime_only_config.get("_superseded_turn_id")+ if superseded_turn_id:+ session_metadata["superseded_turn_id"] = str(superseded_turn_id)+ if runtime_only_config.get("_regenerate"):+ session_metadata["regenerate"] = Trueawait self._persist_and_publish(execution,StreamEvent(type=StreamEventType.SESSION,source="turn_runtime",- metadata={"session_id": session["id"], "turn_id": turn["id"]},+ metadata=session_metadata,),)async with self._lock:@@ -325,6 +351,102 @@ class TurnRuntimeManager:execution.task = asyncio.create_task(self._run_turn(execution))return session, turn+ async def regenerate_last_turn(+ self,+ session_id: str,+ overrides: dict[str, Any] | None = None,+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ """Re-run the prior user message in ``session_id``.++ Deletes the trailing assistant message (if any), then dispatches a new+ turn with ``_persist_user_message=False`` and ``_regenerate=True`` so+ the runtime knows not to duplicate the user row or refresh long-term+ memory a second time. The original user message stays in place.+ """+ session_id = str(session_id or "").strip()+ if not session_id:+ raise RuntimeError("nothing_to_regenerate")++ session = await self.store.get_session(session_id)+ if session is None:+ raise RuntimeError("nothing_to_regenerate")++ active = await self.store.get_active_turn(session_id)+ if active is not None:+ raise RuntimeError("regenerate_busy")++ last_user = await self.store.get_last_message(session_id, role="user")+ if last_user is None:+ raise RuntimeError("nothing_to_regenerate")++ last_message = await self.store.get_last_message(session_id)+ previous_turn_id: str | None = None+ if last_message is not None and last_message.get("role") == "assistant":+ for event in last_message.get("events") or []:+ turn_id = str((event or {}).get("turn_id") or "")+ if turn_id:+ previous_turn_id = turn_id+ break+ await self.store.delete_message(int(last_message["id"]))++ preferences = session.get("preferences") or {}+ overrides = overrides or {}++ capability = str(+ overrides.get("capability")+ or last_user.get("capability")+ or preferences.get("capability")+ or "chat"+ )+ tools = list(+ overrides.get("tools")+ if overrides.get("tools") is not None+ else preferences.get("tools") or []+ )+ knowledge_bases = list(+ overrides.get("knowledge_bases")+ if overrides.get("knowledge_bases") is not None+ else preferences.get("knowledge_bases") or []+ )+ language = str(+ overrides.get("language")+ or preferences.get("language")+ or "en"+ )++ config: dict[str, Any] = dict(overrides.get("config") or {})+ config.update(+ {+ "_persist_user_message": False,+ "_regenerate": True,+ "_regenerated_from_message_id": int(last_user["id"]),+ }+ )+ if previous_turn_id:+ config["_superseded_turn_id"] = previous_turn_id++ payload: dict[str, Any] = {+ "session_id": session_id,+ "capability": capability,+ "content": str(last_user.get("content", "") or ""),+ "tools": tools,+ "knowledge_bases": knowledge_bases,+ "language": language,+ "attachments": list(last_user.get("attachments") or []),+ "notebook_references": list(+ overrides.get("notebook_references")+ if overrides.get("notebook_references") is not None+ else preferences.get("notebook_references") or []+ ),+ "history_references": list(+ overrides.get("history_references")+ if overrides.get("history_references") is not None+ else preferences.get("history_references") or []+ ),+ "config": config,+ }+ return await self.start_turn(payload)+async def cancel_turn(self, turn_id: str) -> bool:async with self._lock:execution = self._executions.get(turn_id)@@ -420,6 +542,9 @@ class TurnRuntimeManager:request_config = dict(payload.get("config", {}) or {})followup_question_context = _extract_followup_question_context(request_config)persist_user_message = _extract_persist_user_message(request_config)+ is_regenerate = _extract_regenerate_flag(request_config)+ request_config.pop("_regenerated_from_message_id", None)+ request_config.pop("_superseded_turn_id", None)raw_user_content = str(payload.get("content", "") or "")notebook_references = payload.get("notebook_references", []) or []history_references = payload.get("history_references", []) or []@@ -629,16 +754,17 @@ class TurnRuntimeManager:events=assistant_events,)await self.store.update_turn_status(turn_id, "completed")- try:- await memory_service.refresh_from_turn(- user_message=raw_user_content,- assistant_message=assistant_content,- session_id=session_id,- capability=capability_name or "chat",- language=str(payload.get("language", "en") or "en"),- )- except Exception:- logger.debug("Failed to refresh lightweight memory", exc_info=True)+ if not is_regenerate:+ try:+ await memory_service.refresh_from_turn(+ user_message=raw_user_content,+ assistant_message=assistant_content,+ session_id=session_id,+ capability=capability_name or "chat",+ language=str(payload.get("language", "en") or "en"),+ )+ except Exception:+ logger.debug("Failed to refresh lightweight memory", exc_info=True)except asyncio.CancelledError:await self.store.update_turn_status(turn_id, "cancelled", "Turn cancelled")await self._persist_and_publish(diff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.pyindex 5a6e33208..bd6f71578 100644--- a/deeptutor_cli/chat.py+++ b/deeptutor_cli/chat.py@@ -11,7 +11,7 @@ from rich.panel import Panelfrom deeptutor.app import DeepTutorApp, TurnRequest-from .common import console, maybe_run, run_turn_and_render+from .common import console, maybe_run, regenerate_and_render, run_turn_and_render@dataclass@@ -78,6 +78,7 @@ async def _chat_repl(state: ChatState) -> None:"[bold]DeepTutor CLI[/]\n""Type a message to chat. Commands:\n"" /quit /session /new\n"+ " /regenerate (alias /retry) — re-run the last user message\n"" /tool on|off <name>\n"" /cap <name>\n"" /kb <name>|none\n"@@ -99,6 +100,21 @@ async def _chat_repl(state: ChatState) -> None:if not user_input:continueif user_input.startswith("/"):+ command = user_input.split(maxsplit=1)[0].lower()+ if command in {"/regenerate", "/retry"}:+ if not state.session_id:+ console.print("[yellow]No active session yet — send a message first.[/]")+ continue+ result = await regenerate_and_render(+ app=client,+ session_id=state.session_id,+ capability=state.capability,+ fmt="rich",+ )+ if result is not None:+ session, _turn = result+ state.session_id = str(session["id"])+ continueshould_continue = _apply_command(user_input, state)if should_continue:continuediff --git a/deeptutor_cli/common.py b/deeptutor_cli/common.pyindex ad4e94441..9c43597d8 100644--- a/deeptutor_cli/common.py+++ b/deeptutor_cli/common.py@@ -75,6 +75,41 @@ async def run_turn_and_render(return session, turn+async def regenerate_and_render(+ *,+ app: DeepTutorApp,+ session_id: str,+ capability: str = "chat",+ fmt: str = "rich",+) -> tuple[dict[str, Any], dict[str, Any]] | None:+ try:+ session, turn = await app.regenerate_last_turn(session_id)+ except RuntimeError as exc:+ reason = str(exc)+ if reason == "regenerate_busy":+ console.print(+ "[yellow]Cannot regenerate while another turn is running. "+ "Wait for it to finish or cancel it first.[/]"+ )+ elif reason == "nothing_to_regenerate":+ console.print("[yellow]Nothing to regenerate yet — send a message first.[/]")+ else:+ console.print(f"[red]Regenerate failed:[/] {reason}")+ return None++ if fmt == "json":+ async for item in app.stream_turn(turn["id"]):+ console.print(json.dumps(item, ensure_ascii=False))+ return session, turn++ await render_turn_stream(app=app, turn_id=turn["id"])+ console.print(+ f"[dim]session={session['id']} turn={turn['id']} capability={capability} (regenerated)[/]",+ highlight=False,+ )+ return session, turn++async def render_turn_stream(*, app: DeepTutorApp, turn_id: str) -> None:content_buf = ""current_stage = ""diff --git a/tests/services/session/test_regenerate.py b/tests/services/session/test_regenerate.pynew file mode 100644index 000000000..c98581908--- /dev/null+++ b/tests/services/session/test_regenerate.py@@ -0,0 +1,373 @@+"""Tests for the chat regenerate-last-turn flow.++Covers the SQLite store helpers added for tail rollback as well as the+``TurnRuntimeManager.regenerate_last_turn`` orchestration: assistant tail+deletion, user-message preservation, ``_persist_user_message`` propagation,+busy/empty session rejection, and skipping the long-term memory refresh on+regeneration.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from unittest.mock import patch++import pytest++from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.services.session.sqlite_store import SQLiteSessionStore+from deeptutor.services.session.turn_runtime import (+ TurnRuntimeManager,+ _extract_regenerate_flag,+)+++async def _noop_refresh(**_kwargs):+ return None+++def store(tmp_path: Path) -> SQLiteSessionStore:+ return SQLiteSessionStore(db_path=tmp_path / "regenerate.db")+++# ---------------------------------------------------------------------------+# _extract_regenerate_flag+# ---------------------------------------------------------------------------+++class TestExtractRegenerateFlag:+ def test_default_is_false(self) -> None:+ assert _extract_regenerate_flag({}) is False++ def test_none_config_is_false(self) -> None:+ assert _extract_regenerate_flag(None) is False++ def test_true_bool(self) -> None:+ config = {"_regenerate": True}+ assert _extract_regenerate_flag(config) is True+ assert "_regenerate" not in config # popped++ def test_true_string(self) -> None:+ assert _extract_regenerate_flag({"_regenerate": "true"}) is True++ def test_one_string(self) -> None:+ assert _extract_regenerate_flag({"_regenerate": "1"}) is True++ def test_false_string(self) -> None:+ assert _extract_regenerate_flag({"_regenerate": "false"}) is False+++# ---------------------------------------------------------------------------+# Store helpers+# ---------------------------------------------------------------------------+++class TestStoreTailRollback:+ def test_delete_message_removes_only_target(self, store: SQLiteSessionStore) -> None:+ session = asyncio.run(store.create_session())+ sid = session["id"]+ m1 = asyncio.run(store.add_message(sid, role="user", content="hi"))+ m2 = asyncio.run(store.add_message(sid, role="assistant", content="hello"))++ deleted = asyncio.run(store.delete_message(m2))+ assert deleted is True++ remaining = asyncio.run(store.get_messages(sid))+ assert [m["id"] for m in remaining] == [m1]+ assert remaining[0]["role"] == "user"++ def test_delete_message_returns_false_when_missing(self, store: SQLiteSessionStore) -> None:+ assert asyncio.run(store.delete_message(99999)) is False++ def test_get_last_message_no_filter(self, store: SQLiteSessionStore) -> None:+ session = asyncio.run(store.create_session())+ sid = session["id"]+ asyncio.run(store.add_message(sid, role="user", content="q1"))+ last_id = asyncio.run(store.add_message(sid, role="assistant", content="a1"))++ last = asyncio.run(store.get_last_message(sid))+ assert last is not None+ assert last["id"] == last_id+ assert last["role"] == "assistant"++ def test_get_last_message_filtered_by_role(self, store: SQLiteSessionStore) -> None:+ session = asyncio.run(store.create_session())+ sid = session["id"]+ u1 = asyncio.run(store.add_message(sid, role="user", content="q1"))+ asyncio.run(store.add_message(sid, role="assistant", content="a1"))+ u2 = asyncio.run(store.add_message(sid, role="user", content="q2"))+ asyncio.run(store.add_message(sid, role="assistant", content="a2"))++ last_user = asyncio.run(store.get_last_message(sid, role="user"))+ assert last_user is not None+ assert last_user["id"] == u2+ assert last_user["content"] == "q2"+ # Sanity: u1 still exists but is not the last user.+ assert u1 != u2++ def test_get_last_message_empty_session(self, store: SQLiteSessionStore) -> None:+ session = asyncio.run(store.create_session())+ assert asyncio.run(store.get_last_message(session["id"])) is None+++# ---------------------------------------------------------------------------+# TurnRuntimeManager.regenerate_last_turn+# ---------------------------------------------------------------------------+++class _FakeStartTurnRecorder:+ """Captures the payload passed to ``start_turn`` without launching it."""++ def __init__(self) -> None:+ self.calls: list[dict[str, Any]] = []++ async def __call__(self, payload: dict[str, Any]) -> tuple[dict, dict]:+ self.calls.append(payload)+ return (+ {"id": payload["session_id"]},+ {"id": "fake-turn", "session_id": payload["session_id"]},+ )+++def _seed_session(+ store: SQLiteSessionStore,+ *,+ user_content: str = "what is 2+2?",+ assistant_content: str | None = "4",+) -> tuple[str, int, int | None]:+ """Create a session with a user (and optional assistant) message."""+ session = asyncio.run(store.create_session())+ sid = session["id"]+ asyncio.run(+ store.update_session_preferences(+ sid,+ {+ "capability": "chat",+ "tools": ["rag"],+ "knowledge_bases": ["kb1"],+ "language": "en",+ },+ )+ )+ user_id = asyncio.run(+ store.add_message(+ sid,+ role="user",+ content=user_content,+ capability="chat",+ attachments=[{"type": "file", "filename": "a.pdf"}],+ )+ )+ assistant_id: int | None = None+ if assistant_content is not None:+ assistant_id = asyncio.run(+ store.add_message(+ sid,+ role="assistant",+ content=assistant_content,+ capability="chat",+ )+ )+ return sid, user_id, assistant_id+++class TestRegenerateLastTurn:+ def test_assistant_tail_is_deleted_and_payload_replays_user(+ self, store: SQLiteSessionStore+ ) -> None:+ sid, user_id, assistant_id = _seed_session(store)+ runtime = TurnRuntimeManager(store=store)+ recorder = _FakeStartTurnRecorder()++ with patch.object(runtime, "start_turn", new=recorder):+ asyncio.run(runtime.regenerate_last_turn(sid))++ assert len(recorder.calls) == 1+ payload = recorder.calls[0]+ assert payload["session_id"] == sid+ assert payload["content"] == "what is 2+2?"+ assert payload["capability"] == "chat"+ assert payload["tools"] == ["rag"]+ assert payload["knowledge_bases"] == ["kb1"]+ assert payload["language"] == "en"+ assert payload["attachments"] == [{"type": "file", "filename": "a.pdf"}]+ assert payload["config"]["_persist_user_message"] is False+ assert payload["config"]["_regenerate"] is True+ assert payload["config"]["_regenerated_from_message_id"] == user_id++ remaining = asyncio.run(store.get_messages(sid))+ assert [m["id"] for m in remaining] == [user_id]+ assert assistant_id is not None and assistant_id not in {m["id"] for m in remaining}++ def test_user_tail_is_kept_and_no_delete(self, store: SQLiteSessionStore) -> None:+ sid, user_id, _ = _seed_session(store, assistant_content=None)+ runtime = TurnRuntimeManager(store=store)+ recorder = _FakeStartTurnRecorder()++ with patch.object(runtime, "start_turn", new=recorder):+ asyncio.run(runtime.regenerate_last_turn(sid))++ assert len(recorder.calls) == 1+ remaining = asyncio.run(store.get_messages(sid))+ assert [m["id"] for m in remaining] == [user_id]++ def test_empty_session_raises_nothing_to_regenerate(self, store: SQLiteSessionStore) -> None:+ session = asyncio.run(store.create_session())+ runtime = TurnRuntimeManager(store=store)++ with pytest.raises(RuntimeError) as exc:+ asyncio.run(runtime.regenerate_last_turn(session["id"]))+ assert str(exc.value) == "nothing_to_regenerate"++ def test_missing_session_raises_nothing_to_regenerate(self, store: SQLiteSessionStore) -> None:+ runtime = TurnRuntimeManager(store=store)+ with pytest.raises(RuntimeError) as exc:+ asyncio.run(runtime.regenerate_last_turn("does-not-exist"))+ assert str(exc.value) == "nothing_to_regenerate"++ def test_active_running_turn_raises_busy(self, store: SQLiteSessionStore) -> None:+ sid, _, _ = _seed_session(store)+ # Create a running turn directly via the store.+ asyncio.run(store.create_turn(sid, capability="chat"))++ runtime = TurnRuntimeManager(store=store)+ with pytest.raises(RuntimeError) as exc:+ asyncio.run(runtime.regenerate_last_turn(sid))+ assert str(exc.value) == "regenerate_busy"++ @pytest.mark.asyncio+ async def test_end_to_end_skips_memory_refresh_and_no_duplicate_user(+ self,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ ) -> None:+ """Run a real turn, regenerate it, and confirm the runtime contracts.++ - The original user message is preserved (no duplicate row).+ - The previous assistant message is replaced.+ - ``memory_service.refresh_from_turn`` is **not** invoked for the+ regenerate turn (it would have been invoked for the original).+ - The new SESSION event carries ``regenerate``/``regenerated_from_message_id``.+ """+ store = SQLiteSessionStore(tmp_path / "regen_e2e.db")+ runtime = TurnRuntimeManager(store)++ class FakeContextBuilder:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def build(self, **_kwargs):+ return SimpleNamespace(+ conversation_history=[],+ conversation_summary="",+ context_text="",+ token_count=0,+ budget=0,+ )++ responses = iter(["original answer", "regenerated answer"])++ class FakeOrchestrator:+ async def handle(self, _context):+ yield StreamEvent(+ type=StreamEventType.CONTENT,+ source="chat",+ stage="responding",+ content=next(responses),+ metadata={"call_kind": "llm_final_response"},+ )+ yield StreamEvent(type=StreamEventType.DONE, source="chat")++ refresh_calls: list[dict[str, Any]] = []++ async def tracking_refresh(**kwargs):+ refresh_calls.append(kwargs)++ monkeypatch.setattr(+ "deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace()+ )+ monkeypatch.setattr(+ "deeptutor.services.session.context_builder.ContextBuilder",+ FakeContextBuilder,+ )+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr(+ "deeptutor.services.memory.get_memory_service",+ lambda: SimpleNamespace(+ build_memory_context=lambda: "",+ refresh_from_turn=tracking_refresh,+ ),+ )++ # First turn — populates user + assistant rows and triggers memory refresh.+ session, first_turn = await runtime.start_turn(+ {+ "type": "start_turn",+ "content": "what is 2+2?",+ "session_id": None,+ "capability": "chat",+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "en",+ "config": {},+ }+ )+ async for _ in runtime.subscribe_turn(first_turn["id"], after_seq=0):+ pass++ sid = session["id"]+ before = await store.get_messages(sid)+ assert [m["role"] for m in before] == ["user", "assistant"]+ assert before[1]["content"] == "original answer"+ original_user_id = before[0]["id"]+ assert len(refresh_calls) == 1++ # Regenerate — must not duplicate user, must replace assistant, must skip memory refresh.+ _, regen_turn = await runtime.regenerate_last_turn(sid)+ events = []+ async for event in runtime.subscribe_turn(regen_turn["id"], after_seq=0):+ events.append(event)++ assert events[0]["type"] == "session"+ session_meta = events[0].get("metadata") or {}+ assert session_meta.get("regenerate") is True+ assert session_meta.get("regenerated_from_message_id") == original_user_id++ after = await store.get_messages(sid)+ assert [m["role"] for m in after] == ["user", "assistant"]+ assert after[0]["id"] == original_user_id+ assert after[1]["content"] == "regenerated answer"+ # Memory refresh must NOT have been called a second time.+ assert len(refresh_calls) == 1++ def test_overrides_take_precedence(self, store: SQLiteSessionStore) -> None:+ sid, _, _ = _seed_session(store)+ runtime = TurnRuntimeManager(store=store)+ recorder = _FakeStartTurnRecorder()++ with patch.object(runtime, "start_turn", new=recorder):+ asyncio.run(+ runtime.regenerate_last_turn(+ sid,+ overrides={+ "tools": ["web_search"],+ "knowledge_bases": [],+ "language": "zh",+ "config": {"temperature": 0.2},+ },+ )+ )++ payload = recorder.calls[0]+ assert payload["tools"] == ["web_search"]+ assert payload["knowledge_bases"] == []+ assert payload["language"] == "zh"+ assert payload["config"]["temperature"] == 0.2+ # Runtime flags must still be set even when overrides supply config.+ assert payload["config"]["_persist_user_message"] is False+ assert payload["config"]["_regenerate"] is Truediff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsxindex f9746ee45..b744f92e6 100644--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx@@ -209,6 +209,7 @@ export default function ChatPage() {setKBs,sendMessage,cancelStreamingTurn,+ regenerateLastMessage,newSession,loadSession,} = useUnifiedChat();@@ -345,19 +346,6 @@ export default function ChatPage() {console.error("Failed to copy assistant message:", error);}}, []);- const replaySnapshot = useCallback(- (snapshot?: MessageRequestSnapshot, configOverride?: Record<string, unknown>) => {- if (!snapshot || state.isStreaming) return;- sendMessage(- snapshot.content, snapshot.attachments, configOverride ?? snapshot.config,- snapshot.notebookReferences, snapshot.historyReferences,- { displayUserMessage: false, persistUserMessage: false, requestSnapshotOverride: snapshot },- snapshot.questionNotebookReferences,- );- shouldAutoScrollRef.current = true;- },- [sendMessage, shouldAutoScrollRef, state.isStreaming],- );const handleAnswerNow = useCallback((snapshot?: MessageRequestSnapshot, assistantMsg?: { content: string; events?: StreamEvent[] }) => {if (!snapshot || !state.isStreaming) return;@@ -634,9 +622,9 @@ export default function ChatPage() {[researchConfig, sendMessage, shouldAutoScrollRef],);- const handleRetryMessage = useCallback((snapshot?: MessageRequestSnapshot) => {- replaySnapshot(snapshot);- }, [replaySnapshot]);+ const handleRegenerateMessage = useCallback(() => {+ regenerateLastMessage();+ }, [regenerateLastMessage]);const handleSetKB = useCallback((kb: string) => { setKBs(kb ? [kb] : []); }, [setKBs]);const handleSelectNotebookPicker = useCallback(() => { setShowNotebookPicker(true); }, []);@@ -724,7 +712,7 @@ export default function ChatPage() {language={state.language}onAnswerNow={handleAnswerNow}onCopyAssistantMessage={copyAssistantMessage}- onRetryMessage={handleRetryMessage}+ onRegenerateMessage={handleRegenerateMessage}onConfirmOutline={handleConfirmOutline}/><div ref={messagesEndRef} className="h-px w-full shrink-0" />diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex 0f56f37c3..f2388e9c2 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -9,7 +9,7 @@ import {Coins,Copy,MessageSquare,- RotateCcw,+ RefreshCcw,X,Zap,type LucideIcon,@@ -411,7 +411,7 @@ export const ChatMessageList = memo(function ChatMessageList({language,onAnswerNow,onCopyAssistantMessage,- onRetryMessage,+ onRegenerateMessage,onConfirmOutline,}: {messages: ChatMessageItem[];@@ -423,7 +423,7 @@ export const ChatMessageList = memo(function ChatMessageList({assistantMsg?: { content: string; events?: StreamEvent[] },) => void;onCopyAssistantMessage: (content: string) => void | Promise<void>;- onRetryMessage: (snapshot?: MessageRequestSnapshot) => void;+ onRegenerateMessage: () => void;onConfirmOutline?: (outline: Array<{ title: string; overview: string }>, topic: string, researchConfig?: Record<string, unknown> | null) => void;}) {const { t } = useTranslation();@@ -472,6 +472,13 @@ export const ChatMessageList = memo(function ChatMessageList({});}, [messages]);+ const lastAssistantIndex = useMemo(() => {+ for (let idx = messages.length - 1; idx >= 0; idx -= 1) {+ if (messages[idx].role === "assistant") return idx;+ }+ return -1;+ }, [messages]);+return (<>{messageRows.map(({ msg, originalIndex, pairedUserMessage }) => {@@ -490,10 +497,13 @@ export const ChatMessageList = memo(function ChatMessageList({const msgDone = !isActiveAssistant;const showActions =msgDone && hasVisibleMarkdownContent(msg.content);- const showRetry =+ const isLastAssistant = i === lastAssistantIndex;+ const showRegenerate =showActions &&- (!pairedUserMessage?.capability || pairedUserMessage?.capability === "chat") &&- Boolean(pairedUserMessage?.requestSnapshot);+ !isStreaming &&+ isLastAssistant &&+ Boolean(pairedUserMessage) &&+ (!pairedUserMessage?.capability || pairedUserMessage?.capability === "chat");// The "Answer now" affordance lives inside the trace panel for the// currently-streaming assistant turn. We hand the panel a thin@@ -537,11 +547,11 @@ export const ChatMessageList = memo(function ChatMessageList({label={t("Copy")}onClick={() => void onCopyAssistantMessage(msg.content)}/>- {showRetry && (+ {showRegenerate && (<RoughActionButton- icon={RotateCcw}- label={t("Retry")}- onClick={() => onRetryMessage(pairedUserMessage?.requestSnapshot)}+ icon={RefreshCcw}+ label="Regenerate"+ onClick={() => onRegenerateMessage()}/>)}</div>diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex dccc4dcd5..671c2f607 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -125,6 +125,7 @@ type Action =attachments?: MessageAttachment[];requestSnapshot?: MessageRequestSnapshot;}+ | { type: "POP_LAST_ASSISTANT"; key: string }| { type: "STREAM_START"; key: string }| { type: "STREAM_EVENT"; key: string; event: StreamEvent }| { type: "STREAM_END"; key: string; status?: SessionRuntimeStatus; turnId?: string | null }@@ -230,6 +231,23 @@ function reducer(state: ProviderState, action: Action): ProviderState {},};}+ case "POP_LAST_ASSISTANT": {+ const session = state.sessions[action.key];+ if (!session || session.messages.length === 0) return state;+ const last = session.messages[session.messages.length - 1];+ if (last.role !== "assistant") return state;+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [action.key]: {+ ...session,+ messages: session.messages.slice(0, -1),+ updatedAt: Date.now(),+ },+ },+ };+ }case "STREAM_START":return {...state,@@ -393,6 +411,7 @@ interface ChatContextValue {questionNotebookReferences?: QuestionNotebookReferencePayload,) => void;cancelStreamingTurn: () => void;+ regenerateLastMessage: () => void;newSession: () => void;loadSession: (sessionId: string) => Promise<void>;selectedSessionId: string | null;@@ -761,6 +780,23 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })dispatch({ type: "STREAM_END", key, status: "cancelled" });}, []);+ const regenerateLastMessage = useCallback(() => {+ const currentState = stateRef.current;+ const key = currentState.selectedKey;+ if (!key) return;+ const session = currentState.sessions[key];+ if (!session || !session.sessionId) return;+ if (session.isStreaming) return;+ const lastUser = [...session.messages].reverse().find((m) => m.role === "user");+ if (!lastUser) return;+ dispatch({ type: "POP_LAST_ASSISTANT", key });+ dispatch({ type: "STREAM_START", key });+ sendThroughRunner(key, {+ type: "regenerate",+ session_id: session.sessionId,+ });+ }, [sendThroughRunner]);+const derivedState = useMemo<ChatState>(() => {const current = ensureSelectedSession(state);return {@@ -817,6 +853,7 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })setLanguage,sendMessage,cancelStreamingTurn,+ regenerateLastMessage,newSession,loadSession,selectedSessionId: derivedState.sessionId,diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.tsindex 624fe4559..2ca774760 100644--- a/web/lib/unified-ws.ts+++ b/web/lib/unified-ws.ts@@ -96,13 +96,20 @@ export interface CancelTurnMessage {turn_id: string;}+export interface RegenerateMessage {+ type: "regenerate";+ session_id: string;+ overrides?: Record<string, unknown>;+}+export type ChatMessage =| StartTurnMessage| SubscribeTurnMessage| SubscribeSessionMessage| ResumeTurnMessage| UnsubscribeMessage- | CancelTurnMessage;+ | CancelTurnMessage+ | RegenerateMessage;// ---- Connection manager ----