Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

31.2 KB
Raw Blame
"""
Unified session history API.
"""

from __future__ import annotations

import asyncio
import logging
import re
from typing import Any, Literal

from fastapi import APIRouter, HTTPException, Query, Request
from pydantic import BaseModel, Field, field_validator

from deeptutor.core.turn_request import TurnRequest
from deeptutor.modules.catalog import module_enabled
from deeptutor.response_languages import validate_reply_language_override
from deeptutor.services.session import get_session_store, get_sqlite_session_store
from deeptutor.services.session.organization import (
    list_all_sessions_snapshot,
    validate_parent_assignment,
)
from deeptutor.services.session.provider_response_state import (
    redact_private_message_metadata as _redact_provider_state_metadata,
)
from deeptutor.services.session.search import MAX_SEARCH_QUERY_CHARS
from deeptutor.services.storage.attachment_store import get_attachment_store

logger = logging.getLogger(__name__)

router = APIRouter()
_LEGACY_TIMED_MEDIA_ID = re.compile(r"^[0-9a-f]{16,64}$")


def _turn_application_service():
    from deeptutor.app.container import get_application_container

    return get_application_container().turns


class SessionStoreCapabilities(BaseModel):
    submission_replacement: bool


@router.get("/capabilities", response_model=SessionStoreCapabilities)
async def session_store_capabilities():
    """Expose operations the configured store can perform atomically."""
    return SessionStoreCapabilities(
        submission_replacement=callable(getattr(get_session_store(), "replace_submission", None))
    )


class SubmissionReplacementRequest(BaseModel):
    original_submission_id: str = Field(min_length=1, max_length=100)
    request: TurnRequest


class SubmissionReplacementResponse(BaseModel):
    status: Literal["started"]
    session_id: str
    submission_id: str
    turn: dict[str, Any]


@router.post("/submission-replacement", response_model=SubmissionReplacementResponse)
async def replace_submission(body: SubmissionReplacementRequest):
    """Resolve admission atomically before an edited retry is sent."""
    try:
        return await _turn_application_service().replace_submission(
            body.original_submission_id, body.request, start=True
        )
    except NotImplementedError as exc:
        raise HTTPException(status_code=501, detail=str(exc)) from exc
    except RuntimeError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc


class SessionRenameRequest(BaseModel):
    title: str = Field(..., min_length=1, max_length=100)


class BranchSelectionRequest(BaseModel):
    """Edit-branch picker state: `{parent_message_id: chosen_child_id}`.

    Stored inside the session preferences blob so it survives reloads
    without a dedicated column.
    """

    selected_branches: dict[str, int] = Field(default_factory=dict)


class SessionOrganizationRequest(BaseModel):
    """User-controlled organization metadata stored with the conversation."""

    workspace_id: str | None = None
    parent_session_id: str | None = None
    session_kind: Literal["chat", "selection_tutor", "immersive_reading"] | None = None
    pinned: bool | None = None
    archived: bool | None = None


class SessionReplyLanguageRequest(BaseModel):
    language: str | None

    @field_validator("language")
    @classmethod
    def _supported_language(cls, value: str | None) -> str | None:
        return validate_reply_language_override(value)


class QuizResultItem(BaseModel):
    question_id: str = ""
    question: str = Field(..., min_length=1)
    question_type: str = ""
    options: dict[str, str] | None = None
    user_answer: str = ""
    correct_answer: str = ""
    explanation: str | None = ""
    difficulty: str | None = ""
    is_correct: bool

    @field_validator("options", mode="before")
    @classmethod
    def _coerce_options(cls, v):
        return v if isinstance(v, dict) else {}

    @field_validator("explanation", "difficulty", mode="before")
    @classmethod
    def _coerce_str(cls, v):
        return v if isinstance(v, str) else ""


class QuizResultsRequest(BaseModel):
    answers: list[QuizResultItem] = Field(default_factory=list)
    turn_id: str = ""


def _format_quiz_results_message(answers: list[QuizResultItem]) -> str:
    total = len(answers)
    correct = sum(1 for item in answers if item.is_correct)
    score_pct = round((correct / total) * 100) if total else 0
    lines = ["[Quiz Performance]"]
    for idx, item in enumerate(answers, 1):
        question = item.question.strip().replace("\n", " ")
        user_answer = (item.user_answer or "").strip() or "(blank)"
        status = "Correct" if item.is_correct else "Incorrect"
        suffix = f" ({status})"
        if not item.is_correct and (item.correct_answer or "").strip():
            suffix = f" ({status}, correct: {(item.correct_answer or '').strip()})"
        qid = f"[{item.question_id}] " if item.question_id else ""
        lines.append(f"{idx}. {qid}Q: {question} -> Answered: {user_answer}{suffix}")
    lines.append(f"Score: {correct}/{total} ({score_pct}%)")
    return "\n".join(lines)


def _legacy_watching_media_id(preferences: dict[str, Any]) -> str:
    watching = (
        preferences.get("workspace_mode") == "immersive_watching"
        or preferences.get("capability") == "immersive_watching"
        or preferences.get("session_kind") == "immersive_watching"
    )
    if not watching:
        return ""
    candidate = str(preferences.get("timed_media_id") or "").strip().lower()
    return candidate if _LEGACY_TIMED_MEDIA_ID.fullmatch(candidate) else ""


async def _normalize_legacy_watching_session(
    store: Any,
    session: dict[str, Any],
    *,
    persist: bool,
) -> bool:
    preferences = session.get("preferences") if isinstance(session.get("preferences"), dict) else {}
    from deeptutor.video_learning.service import TimedMediaNotFound

    timed_media_id = _legacy_watching_media_id(preferences)
    if not timed_media_id:
        for message in reversed(session.get("messages") or []):
            metadata = message.get("metadata") or {}
            snapshot = metadata.get("request_snapshot") or metadata.get("requestSnapshot") or {}
            recovered = snapshot.get("timedMediaId") or snapshot.get("timed_media_id")
            candidate = _legacy_watching_media_id({**preferences, "timed_media_id": recovered})
            if candidate:
                timed_media_id = candidate
                break
    if not timed_media_id:
        normalized = {
            **preferences,
            "capability": "chat",
            "workspace_mode": "",
            "session_kind": "chat",
            "legacy_watching_unavailable": True,
        }
        session["preferences"] = normalized
        if persist:
            await store.update_session_preferences(str(session.get("id")), normalized)
        return True
    try:
        from deeptutor.video_learning.reading_migration import WatchingToReadingMigration

        migrated = await WatchingToReadingMigration().migrate(
            timed_media_id,
            session_id=str(session.get("id") or ""),
            session_title=str(session.get("title") or "Imported video conversation"),
        )
    except TimedMediaNotFound:
        normalized = {
            **preferences,
            "capability": "chat",
            "workspace_mode": "",
            "session_kind": "chat",
            "legacy_watching_unavailable": True,
        }
        normalized.pop("timed_media_viewport", None)
        session["preferences"] = normalized
        if persist:
            await store.update_session_preferences(str(session.get("id")), normalized)
        return True
    except Exception:
        logger.warning(
            "Could not migrate legacy Watching session %s to Reading",
            session.get("id"),
            exc_info=True,
        )
        return False
    normalized = {
        **preferences,
        "capability": "chat",
        "workspace_mode": "immersive_reading",
        "session_kind": "immersive_reading",
        "reading_workspace_id": migrated.reading_workspace_id,
        "reading_material_id": migrated.reading_material_id,
        # Kept as provenance and a provider-cache pointer; it is no longer routing state.
        "timed_media_id": timed_media_id,
    }
    normalized.pop("timed_media_viewport", None)
    session["preferences"] = normalized
    if persist:
        await store.update_session_preferences(str(session.get("id")), normalized)
    return True


@router.get("")
async def list_sessions(
    limit: int = Query(default=50, ge=1, le=200),
    offset: int = Query(default=0, ge=0),
    workspace_id: str | None = Query(default=None),
    all_workspaces: bool = False,
):
    if all_workspaces:
        # Account management (Settings › Archive) only; every navigation
        # surface lists the request's own workspace.
        from deeptutor.services.workspace.navigation import session_index

        return await session_index(limit, offset)
    store = get_session_store()
    sessions = await store.list_sessions(
        limit=limit,
        offset=offset,
        **({"workspace_id": workspace_id} if workspace_id is not None else {}),
    )
    return {"sessions": _with_source_workspace(sessions)}


def _with_source_workspace(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Name the store a row was read from; a legacy preference may disagree."""
    from deeptutor.services.workspace.context import current_workspace_id

    workspace_id = current_workspace_id()
    return [{**row, "content_workspace_id": workspace_id} for row in rows]


@router.get("/search")
async def search_sessions(
    q: str = Query(..., min_length=1, max_length=MAX_SEARCH_QUERY_CHARS),
    limit: int = Query(default=50, ge=1, le=100),
    offset: int = Query(default=0, ge=0),
):
    """Search titles and persisted user/assistant messages for a literal term."""
    if not q.strip():
        raise HTTPException(status_code=400, detail="Search query cannot be empty")
    result = await get_session_store().search_sessions(q, limit=limit, offset=offset)
    return {
        "sessions": _with_source_workspace(result["sessions"]),
        "total": result["total"],
        "limit": limit,
        "offset": offset,
    }


# Cap (in characters) for a single event payload returned to the UI. RAG
# tools can attach whole KB documents to ``tool_result``/``observation``
# events; the frontend TraceSurface only needs a preview, and the LLM context
# is built from a separate content-only store, so capping here never affects
# model input.
MAX_EVENT_PAYLOAD = 1024 * 1024
_TRUNCATION_NOTICE = "\n\n[... content truncated]"
_TRUNCATABLE_EVENT_TYPES = ("tool_result", "observation")


def _redact_private_message_metadata(messages: list[dict[str, Any]]) -> None:
    """Remove provider-only state before session details cross the API."""
    _redact_provider_state_metadata(messages)


def _attach_orphaned_failed_turns(
    messages: list[dict[str, Any]], turns: list[dict[str, Any]]
) -> None:
    """Expose a failed turn beside its saved user row when no reply exists.

    Older rows have no turn id, so the first user row written during the
    turn is the safe fallback. A failed preflight with no saved user row is
    deliberately omitted rather than attached to an unrelated question.
    """
    users = [
        (index, message) for index, message in enumerate(messages) if message.get("role") == "user"
    ]
    for turn in turns:
        turn_id = str(turn.get("turn_id") or turn.get("id") or "")
        started = float(turn.get("created_at") or 0)
        finished = float(turn.get("finished_at") or turn.get("updated_at") or 0)
        match = next(
            (
                (index, message)
                for index, message in users
                if str((message.get("metadata") or {}).get("turn_id") or "") == turn_id
            ),
            None,
        )
        if match is None:
            match = next(
                (
                    (index, message)
                    for index, message in users
                    if started <= float(message.get("created_at") or 0) <= finished
                ),
                None,
            )
        if match is None:
            continue
        user_index, user = match
        next_user_index = next((index for index, _ in users if index > user_index), len(messages))
        # A subsequent retry may have answered this same user row. Its real
        # assistant bubble wins; showing an earlier failure beside it would
        # tell the learner that the answered question is still broken. Legacy
        # PocketBase rows have no parent link, so use their linear position
        # only when the parent field is absent, and only after the failure.
        if any(
            message.get("role") == "assistant"
            and (
                (
                    str(message.get("parent_message_id") or "") == str(user.get("id") or "")
                    and float(message.get("created_at") or 0) >= started
                )
                or (
                    "parent_message_id" not in message
                    and user_index < index < next_user_index
                    and float(message.get("created_at") or 0) >= finished
                )
            )
            for index, message in enumerate(messages)
        ):
            continue
        metadata = user.get("metadata")
        if not isinstance(metadata, dict):
            metadata = {}
            user["metadata"] = metadata
        previous = metadata.get("orphaned_failed_turn")
        if isinstance(previous, dict) and float(previous.get("finished_at") or 0) > finished:
            continue
        metadata["orphaned_failed_turn"] = {
            "turn_id": turn_id,
            "error": str(turn.get("error") or ""),
            "failure_code": str(turn.get("failure_code") or ""),
            "retryable": bool(turn.get("retryable")),
            "finished_at": finished,
        }


def _truncate_oversized_events(
    messages: list[dict[str, Any]], limit: int = MAX_EVENT_PAYLOAD
) -> None:
    """Cap oversized ``tool_result``/``observation`` payloads in place.

    The session store already returns each message's events as a parsed
    ``events`` list (see ``SqliteSessionStore._serialize_message``), so we
    mutate that list directly. Only the UI rendering path is affected.
    """

    def _cap(container: dict[str, Any], field: str) -> bool:
        value = container.get(field)
        if isinstance(value, str) and len(value) > limit:
            container[field] = value[:limit] + _TRUNCATION_NOTICE
            return True
        return False

    for msg in messages:
        events = msg.get("events")
        if not isinstance(events, list):
            continue
        for event in events:
            if not isinstance(event, dict) or event.get("type") not in _TRUNCATABLE_EVENT_TYPES:
                continue
            truncated = _cap(event, "content")
            tool_metadata = (event.get("metadata") or {}).get("tool_metadata")
            if isinstance(tool_metadata, dict):
                for field in ("content", "answer"):
                    truncated = _cap(tool_metadata, field) or truncated
            if truncated:
                event["_truncated"] = True


@router.get("/recycle-bin")
async def list_recycle_bin(
    limit: int = Query(default=50, ge=1, le=200),
    offset: int = Query(default=0, ge=0),
):
    store = get_session_store()
    sessions = await store.list_deleted_sessions(limit=limit, offset=offset)
    return {"sessions": sessions}


@router.post("/{session_id}/migrate-watching")
async def migrate_watching_session(session_id: str):
    from deeptutor.services.workspace.activity import workspace_writer

    @workspace_writer
    async def migrate():
        store = get_session_store()
        session = await store.get_session_with_messages(session_id)
        if session is None:
            raise HTTPException(status_code=404, detail="Session not found")
        preferences = session.get("preferences") or {}
        if any(
            preferences.get(key) == "immersive_watching"
            for key in ("capability", "workspace_mode", "session_kind")
        ):
            if not await _normalize_legacy_watching_session(store, session, persist=True):
                raise HTTPException(
                    status_code=409,
                    detail="The legacy video could not be opened in Reading. The original conversation is preserved.",
                )
        return await get_session(session_id)

    return await migrate()


@router.get("/{session_id}")
async def get_session(session_id: str):
    store = get_session_store()
    session = await store.get_session_with_messages(session_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")
    _attach_orphaned_failed_turns(
        session.get("messages", []), await store.list_orphaned_failed_turns(session_id)
    )
    _redact_private_message_metadata(session.get("messages", []))
    _truncate_oversized_events(session.get("messages", []))
    return session


@router.get("/{session_id}/organization")
async def get_session_organization(session_id: str):
    """Title, status and preferences without the transcript.

    The chat header reads this to show the conversation's own menu (pinned,
    archived, filed under) — refetching the full message list for that would
    cost a long conversation its whole history on every sidebar change.
    """
    store = get_session_store()
    session = await store.get_session(session_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")
    return {"session": session}


@router.get("/{session_id}/threads")
async def list_session_threads(session_id: str):
    """Little Tutor threads opened from this conversation, newest first."""
    store = get_session_store()
    if await store.get_session(session_id) is None:
        raise HTTPException(status_code=404, detail="Session not found")
    candidates = await list_all_sessions_snapshot(store)
    threads = [
        row
        for row in candidates
        if str((row.get("preferences") or {}).get("parent_session_id") or "") == session_id
        and (row.get("preferences") or {}).get("session_kind") == "selection_tutor"
    ]
    threads.sort(key=lambda row: float(row.get("updated_at") or 0), reverse=True)
    return {"threads": _with_source_workspace(threads)}


@router.get("/{session_id}/messages/{message_id}/events")
async def get_message_events(
    session_id: str,
    message_id: str,
    after_seq: int = Query(default=0, ge=0),
    limit: int = Query(default=500, ge=1, le=1000),
):
    store = get_session_store()
    trace = await store.get_message_trace(session_id, message_id, after_seq, limit)
    if trace is None:
        raise HTTPException(status_code=404, detail="Message not found")
    return trace


@router.get("/{session_id}/ask-hint")
async def get_session_ask_hint(session_id: str) -> dict[str, Any]:
    """One line the user is likely to type next, for the home composer placeholder."""
    from deeptutor.services.chat_hints import get_ask_hint

    return await get_ask_hint(session_id)


@router.patch("/{session_id}")
async def rename_session(session_id: str, payload: SessionRenameRequest):
    store = get_session_store()
    updated = await store.update_session_title(session_id, payload.title)
    if not updated:
        raise HTTPException(status_code=404, detail="Session not found")
    # The reader keeps its own list of a collection's conversations; the
    # sidebar is where they are renamed, so the list has to hear about it.
    try:
        if module_enabled("reading"):
            from deeptutor.reading.catalog_store import ReadingCatalogStore

            await asyncio.to_thread(
                ReadingCatalogStore().retitle_session, session_id, payload.title
            )
    except Exception:
        logger.exception("failed to retitle reading conversation %s", session_id)
    session = await store.get_session(session_id)
    return {"session": session}


@router.patch("/{session_id}/reply-language")
async def update_session_reply_language(session_id: str, payload: SessionReplyLanguageRequest):
    """Fix this conversation's reply language, or return to the account default."""
    store = get_session_store()
    if await store.get_session(session_id) is None:
        raise HTTPException(status_code=404, detail="Session not found")
    updated = await store.update_session_preferences(
        session_id, {"reply_language_override": payload.language}
    )
    session = await store.get_session(session_id)
    if not updated or session is None:
        raise HTTPException(status_code=404, detail="Session not found")
    return {"session": session}


@router.patch("/{session_id}/organization")
async def update_session_organization(
    session_id: str, payload: SessionOrganizationRequest, request: Request = None
):
    store = get_session_store()
    session = await store.get_session(session_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    updates: dict[str, Any] = {}
    fields = payload.model_fields_set
    if "workspace_id" in fields:
        from deeptutor.services.workspace import WorkspaceError, get_content_workspace_service

        workspace_id = str(payload.workspace_id or "").strip()
        if workspace_id:
            try:
                service = get_content_workspace_service()
                service.validate_chat_binding(workspace_id)
                if workspace_id == service.general_binding().workspace_id:
                    workspace_id = ""
            except WorkspaceError as exc:
                raise HTTPException(status_code=400, detail=str(exc)) from exc
        if await store.get_active_turn(session_id) is not None:
            raise HTTPException(
                status_code=409, detail="Wait for the active turn before moving this conversation."
            )
        if (session.get("preferences") or {}).get("parent_session_id"):
            raise HTTPException(status_code=400, detail="Move the parent conversation instead.")
        from deeptutor.services.workspace.context import get_workspace_scope

        current_scope = get_workspace_scope()
        if current_scope is not None and current_scope.workspace_id != workspace_id:
            # A move changes the store. Do not silently drop other fields or
            # validate their foreign keys against the source and apply them in
            # the destination. Reject the whole request before copying data.
            if fields - {"workspace_id"}:
                raise HTTPException(
                    status_code=400,
                    detail="Move the conversation separately from other organization changes.",
                )
            from deeptutor.api.routers.workspace import _data_operation
            from deeptutor.services.workspace.session_move import move_chat

            # Upgrade this request's shared activity lease. The exclusive
            # nonblocking lease rejects any concurrent writer before copying.
            if request is not None:
                handle = getattr(request.state, "workspace_activity", None)
                if handle is not None:
                    handle.close()
                    request.state.workspace_activity = None
            try:
                moved = await _data_operation(move_chat, session_id, workspace_id)
            except WorkspaceError as exc:
                raise HTTPException(status_code=409, detail=str(exc)) from exc
            return {"session": moved}
        updates["workspace_id"] = workspace_id or None
    if "parent_session_id" in fields:
        parent_id = str(payload.parent_session_id or "").strip()
        if parent_id == session_id:
            raise HTTPException(status_code=400, detail="A session cannot be its own parent")
        if parent_id:
            try:
                await validate_parent_assignment(
                    store,
                    session_id=session_id,
                    parent_session_id=parent_id,
                )
            except LookupError as exc:
                raise HTTPException(status_code=404, detail="Parent session not found") from exc
            except ValueError as exc:
                raise HTTPException(status_code=400, detail=str(exc)) from exc
        updates["parent_session_id"] = parent_id
    if "session_kind" in fields:
        updates["session_kind"] = payload.session_kind or "chat"
    if "pinned" in fields:
        updates["pinned"] = bool(payload.pinned)
    if "archived" in fields:
        updates["archived"] = bool(payload.archived)

    if updates:
        await store.update_session_preferences(session_id, updates)
        cascade_updates = {
            key: updates[key] for key in ("archived", "workspace_id") if key in updates
        }
        if cascade_updates:
            # Selected-text tutor threads stay with their source conversation.
            candidates = await list_all_sessions_snapshot(store)
            for candidate in candidates:
                prefs = candidate.get("preferences") or {}
                if str(prefs.get("parent_session_id") or "") == session_id:
                    await store.update_session_preferences(candidate["session_id"], cascade_updates)
    refreshed = await store.get_session(session_id)
    return {"session": refreshed}


@router.delete("/{session_id}")
async def delete_session(session_id: str):
    store = get_session_store()
    if await store.get_session(session_id) is None:
        raise HTTPException(status_code=404, detail="Session not found")

    # Tutor threads belong to their parent conversation. Snapshot before any
    # deletion changes pagination, and walk descendants without revisiting cycles.
    candidates = await list_all_sessions_snapshot(store)
    children: dict[str, list[str]] = {}
    for row in candidates:
        parent = str((row.get("preferences") or {}).get("parent_session_id") or "")
        children.setdefault(parent, []).append(row["session_id"])
    ordered = [session_id]
    seen = {session_id}
    for parent in ordered:
        for child in children.get(parent, []):
            if child not in seen:
                seen.add(child)
                ordered.append(child)

    list_active_turns = getattr(store, "list_active_turns", None)
    if callable(list_active_turns):
        turns = _turn_application_service()
        for target in ordered:
            for turn in await list_active_turns(target):
                if not await turns.cancel_turn_and_wait(turn["id"]):
                    raise HTTPException(
                        status_code=409,
                        detail="Active conversation turn could not be stopped before deletion",
                    )
    for target in reversed(ordered):
        if not await store.delete_session(target):
            raise HTTPException(status_code=409, detail="Unable to delete conversation")
        await _cleanup_deleted_session(target)
    return {"deleted": True, "session_id": session_id}


async def _cleanup_deleted_session(session_id: str) -> None:
    try:
        if module_enabled("mastery"):
            from deeptutor.learning.storage import LearningStore

            await asyncio.to_thread(LearningStore().detach_session, session_id)
    except Exception:
        logger.exception("failed to detach mastery paths for session %s", session_id)
    try:
        await get_attachment_store().delete_session(session_id)
    except Exception:
        logger.exception("failed to clean up attachments for session %s", session_id)
    try:
        if module_enabled("reading"):
            from deeptutor.reading.catalog_store import ReadingCatalogStore

            await asyncio.to_thread(ReadingCatalogStore().forget_session, session_id)
    except Exception:
        logger.exception("failed to detach reading collections for session %s", session_id)


@router.post("/{session_id}/restore")
async def restore_session(session_id: str):
    store = get_session_store()
    restored = await store.restore_session(session_id)
    if not restored:
        raise HTTPException(status_code=404, detail="Session not found in recycle bin")
    refreshed = await store.get_session(session_id)
    return {"restored": True, "session": refreshed}


@router.delete("/{session_id}/purge")
async def purge_session(session_id: str):
    store = get_session_store()
    purged = await store.hard_delete_session(session_id)
    if not purged:
        raise HTTPException(status_code=404, detail="Session not found in recycle bin")
    await _cleanup_deleted_session(session_id)
    from deeptutor.services.task_board import get_task_board_store
    from deeptutor.services.workspace.context import current_workspace_id

    await asyncio.to_thread(
        get_task_board_store(migrate_legacy=False).remove_session,
        current_workspace_id(),
        session_id,
    )
    return {"purged": True, "session_id": session_id}


@router.put("/{session_id}/branch-selection")
async def update_branch_selection(session_id: str, payload: BranchSelectionRequest):
    store = get_sqlite_session_store()
    session = await store.get_session(session_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")
    updated = await store.update_session_preferences(
        session_id, {"selected_branches": dict(payload.selected_branches)}
    )
    if not updated:
        raise HTTPException(status_code=404, detail="Session not found")
    return {"selected_branches": payload.selected_branches}


@router.delete("/{session_id}/messages/{message_id}")
async def delete_turn_by_message(session_id: str, message_id: int):
    store = get_sqlite_session_store()
    result = await store.delete_turn_by_message(session_id, message_id)
    if result["was_active"]:
        raise HTTPException(
            status_code=409,
            detail="Cannot delete a message while its turn is running or waiting for input",
        )
    if not result["deleted"]:
        raise HTTPException(status_code=404, detail="Message not found")
    attachment_store = get_attachment_store()
    for aid in result["attachment_ids"]:
        try:
            await attachment_store.delete_attachment(session_id, aid)
        except Exception:
            logger.exception("failed to delete attachment %s for session %s", aid, session_id)
    return result


@router.post("/{session_id}/quiz-results")
async def record_quiz_results(session_id: str, payload: QuizResultsRequest):
    if not payload.answers:
        raise HTTPException(status_code=400, detail="Quiz results are required")
    store = get_sqlite_session_store()
    session = await store.get_session(session_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")
    content = _format_quiz_results_message(payload.answers)
    await store.add_message(
        session_id=session_id,
        role="user",
        content=content,
        capability="deep_question",
    )
    notebook_count = 0
    try:
        notebook_count = await store.upsert_notebook_entries(
            session_id,
            [{**item.model_dump(), "turn_id": payload.turn_id} for item in payload.answers],
        )
    except Exception:
        logger.warning(
            "Failed to upsert notebook entries for session %s", session_id, exc_info=True
        )
    return {
        "recorded": True,
        "session_id": session_id,
        "answer_count": len(payload.answers),
        "notebook_count": notebook_count,
        "content": content,
    }