DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(partners): record wrong questions into the question bank (#1244)
ZQR1101ed6b5da1b976
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.pyindex 7e1a03831..ea2517ce1 100644--- a/deeptutor/agents/_shared/tool_composition.py+++ b/deeptutor/agents/_shared/tool_composition.py@@ -352,6 +352,23 @@ def user_has_question_bank() -> bool:return False+def partner_can_record_questions() -> bool:+ """Whether this turn runs inside a partner conversation.++ Partner turns mount ``question_bank`` even when the bank is still empty:+ recording the first wrong question is exactly the point (#1244) — the+ tool's ``record`` action files the mistake the learner just owned up to+ into the bank their family reviews. The partner context is read lazily+ (import-time this would be a cycle through the partners package).+ """+ try:+ from deeptutor.services.partners.interaction import get_partner_turn_context++ return get_partner_turn_context() is not None+ except Exception:+ return False++__all__ = ["AUTO_MOUNTED_TOOLS","ToolMountFlags",@@ -359,6 +376,7 @@ __all__ = ["admin_enabled_optional_tools","compose_enabled_tools","default_optional_tools",+ "partner_can_record_questions","user_has_mastery_topics","user_has_memory","user_has_notebooks",diff --git a/deeptutor/agents/loop/pipeline.py b/deeptutor/agents/loop/pipeline.pyindex c8ce3b00d..7c86d1541 100644--- a/deeptutor/agents/loop/pipeline.py+++ b/deeptutor/agents/loop/pipeline.py@@ -31,6 +31,7 @@ from deeptutor.agents._shared.tool_composition import (ToolMountFlags,compose_enabled_tools,default_optional_tools,+ partner_can_record_questions,user_has_mastery_topics,user_has_memory,user_has_notebooks,@@ -698,7 +699,11 @@ class AgenticLoopPipeline:has_sources=False,has_memory=user_has_memory(),has_notebooks=user_has_notebooks(),- has_question_bank=user_has_question_bank(),+ # A partner turn mounts the bank even when it is still empty:+ # the tool's record action must be available to file the FIRST+ # wrong question the learner owns up to (#1244). Product chat+ # keeps the entries-exist gate.+ has_question_bank=user_has_question_bank() or partner_can_record_questions(),has_skills=bool(context.skills_manifest),has_deferred_tools=getattr(self, "_deferred_loader", None) is not None,has_exec=getattr(self, "_exec_enabled", False),diff --git a/deeptutor/api/routers/question_notebook.py b/deeptutor/api/routers/question_notebook.pyindex 7751ba324..6e7352c71 100644--- a/deeptutor/api/routers/question_notebook.py+++ b/deeptutor/api/routers/question_notebook.py@@ -18,7 +18,9 @@ from deeptutor.services.storage import get_attachment_storelogger = logging.getLogger(__name__)router = APIRouter()-AssessmentSource = Literal["deep_question", "mastery_path", "immersive_reading", "book"]+AssessmentSource = Literal[+ "deep_question", "mastery_path", "immersive_reading", "book", "partner_chat"+]ScoreTrend = Literal["new", "improved", "declined", "unchanged"]diff --git a/deeptutor/services/partners/interaction.py b/deeptutor/services/partners/interaction.pyindex 560d9bff4..a17af9a45 100644--- a/deeptutor/services/partners/interaction.py+++ b/deeptutor/services/partners/interaction.py@@ -115,6 +115,9 @@ class PartnerTurnContext:store: PartnerSessionStoreown_memory: PathServiceshared_memory: PathService+ #: Display name of the partner, for surfaces that label content with it+ #: (e.g. the question-bank session a partner records mistakes into).+ partner_name: str = ""@propertydef actor_id(self) -> str | None:@@ -132,6 +135,7 @@ def build_partner_turn_context(store: PartnerSessionStore,*,legacy_own_memory: PathService,+ partner_name: str = "",) -> PartnerTurnContext:actor_id = personal_actor_id(actor)if actor_id is None:@@ -141,6 +145,7 @@ def build_partner_turn_context(store=store,own_memory=legacy_own_memory,shared_memory=get_admin_path_service(),+ partner_name=partner_name,)assert actor is not None@@ -154,6 +159,7 @@ def build_partner_turn_context(store=store,own_memory=PathService(workspace_root=private_workspace),shared_memory=get_path_service_for_scope(actor.scope),+ partner_name=partner_name,)diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.pyindex b117ecece..6aef941cd 100644--- a/deeptutor/services/partners/runtime.py+++ b/deeptutor/services/partners/runtime.py@@ -457,6 +457,7 @@ class PartnerRunner:msg.actor,store,legacy_own_memory=get_current_path_service(),+ partner_name=self.config.name,)with partner_turn_context(turn_context):event_stream = get_turn_engine().execute(context)diff --git a/deeptutor/services/session/__init__.py b/deeptutor/services/session/__init__.pyindex 715532916..fe66ac69d 100644--- a/deeptutor/services/session/__init__.py+++ b/deeptutor/services/session/__init__.py@@ -4,6 +4,7 @@ from .protocol import SessionStoreProtocolfrom .sqlite_store import (SQLiteSessionStore,get_sqlite_session_store,+ get_sqlite_session_store_for,make_imported_session_id,)from .turn_runtime import TurnRuntimeManager, get_turn_runtime_manager@@ -43,6 +44,7 @@ __all__ = ["TurnRuntimeManager","get_session_store","get_sqlite_session_store",+ "get_sqlite_session_store_for","get_turn_runtime_manager","make_imported_session_id",]diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex 53420b9e0..ab8b3fbee 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -96,7 +96,9 @@ def _json_loads(value: str | None, default: Any) -> Any:# this id prefix as their discriminator (see ``SQLiteSessionStore._WHERE_*``)._IMPORTED_ID_PREFIX = "imported_"_ID_SAFE = re.compile(r"[^A-Za-z0-9_-]")-ASSESSMENT_SOURCES = frozenset({"deep_question", "mastery_path", "immersive_reading", "book"})+ASSESSMENT_SOURCES = frozenset(+ {"deep_question", "mastery_path", "immersive_reading", "book", "partner_chat"}+)SCORE_TRENDS = frozenset({"new", "improved", "declined", "unchanged"})ACTIVE_TURN_STATUSES = frozenset({"queued", "running", "waiting_input"})TERMINAL_TURN_STATUSES = frozenset({"completed", "failed", "cancelled"})@@ -737,6 +739,33 @@ class SQLiteSessionStore:) -> dict[str, Any]:return await self._run(self._create_session_sync, title, session_id)+ async def ensure_notebook_session(self, session_id: str, title: str) -> bool:+ """Insert a placeholder session row so notebook-only sources can file+ entries against it (partner chat has no rows in this store otherwise).++ Returns ``True`` when a row was created, ``False`` when it existed.+ """+ return await self._run(self._ensure_notebook_session_sync, session_id, title)++ def _ensure_notebook_session_sync(self, session_id: str, title: str) -> bool:+ resolved_id = (session_id or "").strip()+ if not resolved_id:+ raise ValueError("ensure_notebook_session requires a session_id")+ now = time.time()+ with self._connect() as conn:+ exists = conn.execute("SELECT id FROM sessions WHERE id = ?", (resolved_id,)).fetchone()+ if exists is not None:+ return False+ conn.execute(+ """+ INSERT INTO sessions (id, title, created_at, updated_at)+ VALUES (?, ?, ?, ?)+ """,+ (resolved_id, (title or "New conversation").strip()[:100], now, now),+ )+ conn.commit()+ return True+def _get_session_sync(self, session_id: str) -> dict[str, Any] | None:with self._connect() as conn:row = conn.execute(@@ -3050,9 +3079,24 @@ def get_sqlite_session_store() -> SQLiteSessionStore:return _instances[key]+def get_sqlite_session_store_for(path_service: Any) -> SQLiteSessionStore:+ """Store for an explicit path service (a scope other than the current one).++ Partner turns run inside the partner's synthetic scope but record question+ bank entries into the learner-facing bank; the target scope's path service+ resolves its chat-history db, and instances stay cached per resolved path.+ """+ db_path = path_service.get_chat_history_db().resolve()+ key = str(db_path)+ if key not in _instances:+ _instances[key] = SQLiteSessionStore(db_path=db_path)+ return _instances[key]++__all__ = ["QuestionBankQuery","SQLiteSessionStore","get_sqlite_session_store",+ "get_sqlite_session_store_for","make_imported_session_id",]diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex 2085fc007..34ca4c931 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -819,13 +819,17 @@ class QuestionBankTool(_PromptHintsMixin, BaseTool):return ToolDefinition(name="question_bank",description=(- "Read and organise the learner's question bank — the graded "- "quiz questions saved under Learning Space → Question Bank. "- "This is where wrong answers and quiz history live; it is NOT "- "the notebook (`write_note`). Use it whenever the learner asks "- "to review, group, file, or tidy their questions or mistakes. "+ "Read, organise, and record the learner's question bank — the "+ "graded quiz questions saved under Learning Space → Question "+ "Bank. This is where wrong answers and quiz history live; it is "+ "NOT the notebook (`write_note`). Use it whenever the learner "+ "asks to review, group, file, or tidy their questions or "+ "mistakes, or when they own up to a mistake worth keeping. ""action='overview' for counts + existing categories; ""action='list' to see entries (each prefixed with its id); "+ "action='record' to save one wrong question from this "+ "conversation into the bank the learner reviews (add "+ "`category` to file it in the same call); ""action='organize' to file entry_ids into a category by name ""(the category is created if it does not exist); ""action='unfile' to remove them; "@@ -837,10 +841,52 @@ class QuestionBankTool(_PromptHintsMixin, BaseTool):type="string",description=("'overview' (counts + categories, needs nothing else), "- "'list', 'organize', 'unfile', or 'bookmark'."+ "'list', 'record', 'organize', 'unfile', or 'bookmark'."),enum=list(QB_ACTIONS),),+ ToolParameter(+ name="question",+ type="string",+ description=(+ "For action='record'. The problem itself, as close to "+ "the learner's wording or photo as possible. Recording "+ "the same question again updates the existing entry."+ ),+ required=False,+ ),+ ToolParameter(+ name="user_answer",+ type="string",+ description=(+ "For action='record'. What the learner answered, if they attempted it."+ ),+ required=False,+ ),+ ToolParameter(+ name="correct_answer",+ type="string",+ description="For action='record'. The correct answer, if known.",+ required=False,+ ),+ ToolParameter(+ name="explanation",+ type="string",+ description=(+ "For action='record'. Why the correct answer is right — "+ "the coaching the learner just received, condensed."+ ),+ required=False,+ ),+ ToolParameter(+ name="is_correct",+ type="boolean",+ description=(+ "For action='record'. Whether the learner answered "+ "correctly. Default false — a recorded mistake."+ ),+ required=False,+ ),ToolParameter(name="filter",type="string",@@ -857,8 +903,10 @@ class QuestionBankTool(_PromptHintsMixin, BaseTool):type="string",description=("Category name. Required for 'organize' / 'unfile'; "- "optional on 'list' to look inside one category. "- "'organize' creates the category when it is new."+ "optional on 'list' to look inside one category and on "+ "'record' to file the new entry in the same call. "+ "'organize' and 'record' create the category when it "+ "is new."),required=False,),@@ -904,6 +952,11 @@ class QuestionBankTool(_PromptHintsMixin, BaseTool):category=str(kwargs.get("category") or ""),search=str(kwargs.get("search") or ""),entry_ids=kwargs.get("entry_ids"),+ question=str(kwargs.get("question") or ""),+ user_answer=str(kwargs.get("user_answer") or ""),+ correct_answer=str(kwargs.get("correct_answer") or ""),+ explanation=str(kwargs.get("explanation") or ""),+ is_correct=bool(kwargs.get("is_correct", False)),bookmarked=bool(kwargs.get("bookmarked", True)),limit=int(kwargs.get("limit") or 20),)diff --git a/deeptutor/tools/question_bank.py b/deeptutor/tools/question_bank.pyindex 9408b003a..5d704ac59 100644--- a/deeptutor/tools/question_bank.py+++ b/deeptutor/tools/question_bank.py@@ -1,4 +1,4 @@-"""Read and organise the learner's question bank from the chat agent.+"""Read, organise, and record the learner's question bank from the chat agent.The question bank is the ``notebook_entries`` table behind``/space/questions``: every quiz question the learner has answered, in@@ -9,7 +9,7 @@ correct answer. Before this tool existed the agent had no way to touchthe bank, so "file my wrong answers into my new question set" landed ina notebook instead: the only writable surface it could see.-One tool, five actions, because the useful sequence is short and always+One tool, six actions, because the useful sequence is short and alwaysthe same — look, then file:* ``overview`` — counts + the existing category names (one call, no ids@@ -22,6 +22,11 @@ the same — look, then file:create-then-file is one more place for the model to drop the ball.* ``unfile`` — take entries back out of a category.* ``bookmark`` — star / unstar entries for later review.+* ``record`` — write one wrong question the learner just owned up to+ in conversation (source ``partner_chat``). Partner turns are the main+ caller (#1244): the tutor coaches a photographed homework mistake and+ the question lands in the bank the family reviews, instead of dying+ in the chat transcript.Every action is dependency-injected with ``store`` so tests never toucha real database, and every failure returns ``ok=False`` with a sentence@@ -31,12 +36,13 @@ the model can act on rather than raising.from __future__ import annotationsfrom dataclasses import dataclass, field+import hashlibimport loggingfrom typing import Anylogger = logging.getLogger(__name__)-ACTIONS = ("overview", "list", "organize", "unfile", "bookmark")+ACTIONS = ("overview", "list", "organize", "unfile", "bookmark", "record")FILTERS = ("all", "wrong", "bookmarked", "uncategorized")@@ -118,11 +124,37 @@ def _render_categories(categories: list[dict[str, Any]]) -> str:async def _resolve_store(store: Any) -> Any:if store is not None:return store+ target_paths = _partner_bank_paths()+ if target_paths is not None:+ from deeptutor.services.session import get_sqlite_session_store_for++ return get_sqlite_session_store_for(target_paths)from deeptutor.services.session import get_sqlite_session_storereturn get_sqlite_session_store()+def _partner_bank_paths() -> Any | None:+ """Path service of the bank a partner turn should read and record into.++ Partner turns execute inside the partner's synthetic user scope, where the+ default store would be the partner's own — a bank nobody can see in the+ web UI. The partner turn context exposes the scope the family actually+ browses (the admin's for IM/admin turns, the assigned learner's own for+ assigned ones); ``None`` outside partner turns, so product chat keeps+ resolving the current user's store.+ """+ try:+ from deeptutor.services.partners.interaction import get_partner_turn_context++ context = get_partner_turn_context()+ except Exception:+ return None+ if context is None:+ return None+ return context.shared_memory++async def _overview(store: Any) -> QuestionBankOutcome:stats = await store.question_bank_stats()categories = await store.list_categories()@@ -328,6 +360,115 @@ async def _bookmark(store: Any, *, entry_ids: Any, bookmarked: bool) -> Question)+MAX_RECORD_QUESTION = 4000+MAX_RECORD_FIELD = 2000+++def _record_question_id(question: str) -> str:+ """Stable content hash so re-recording the same mistake updates the row+ (the store dedups on ``session_id + turn_id + question_id``) instead of+ piling up duplicates each time the learner revisits it."""+ normalized = " ".join(question.split()).casefold()+ return "pq_" + hashlib.sha1(normalized.encode("utf-8")).hexdigest()[:16]+++def _partner_record_session() -> tuple[str, str]:+ """Stable ``(session_id, title)`` naming one partner pairing's mistakes.++ Deterministic per partner + partner-of pairing so every recorded mistake+ lands in the same notebook session the family can review as one list.+ """+ partner_id = ""+ actor_id = ""+ name = ""+ try:+ from deeptutor.services.partners.interaction import get_partner_turn_context++ context = get_partner_turn_context()+ except Exception:+ context = None+ if context is not None:+ partner_id = str(getattr(context, "partner_id", "") or "")+ actor_id = str(getattr(context, "actor_id", "") or "")+ name = str(getattr(context, "partner_name", "") or "").strip()+ session_id = f"partner-notebook:{partner_id or 'unknown'}:{actor_id or 'admin'}"+ if name:+ title = f"{name} (Partner)"+ elif partner_id:+ title = f"Partner {partner_id} notebook"+ else:+ title = "Partner notebook"+ return session_id, title+++async def _record(+ store: Any,+ *,+ question: str,+ user_answer: str,+ correct_answer: str,+ explanation: str,+ question_type: str,+ is_correct: bool,+ category: str,+) -> QuestionBankOutcome:+ text = " ".join(str(question or "").split())+ if not text:+ return QuestionBankOutcome(+ ok=False,+ action="record",+ error="`question` is required — the problem as the learner wrote or photographed it.",+ )+ session_id, session_title = _partner_record_session()+ try:+ await store.ensure_notebook_session(session_id, session_title)+ except Exception:+ logger.warning("question_bank: could not ensure a notebook session", exc_info=True)+ return QuestionBankOutcome(+ ok=False,+ action="record",+ error="The question bank is not available in this conversation; nothing was recorded.",+ )+ item = {+ "question_id": _record_question_id(text),+ "question": text[:MAX_RECORD_QUESTION],+ "question_type": str(question_type or "").strip()[:100],+ "correct_answer": _truncate(correct_answer, MAX_RECORD_FIELD),+ "explanation": _truncate(explanation, MAX_RECORD_FIELD),+ "user_answer": _truncate(user_answer, MAX_RECORD_FIELD),+ "source": "partner_chat",+ "is_correct": bool(is_correct),+ }+ upserted = await store.upsert_notebook_entries(session_id, [item])+ if not upserted:+ return QuestionBankOutcome(+ ok=False,+ action="record",+ error="The bank rejected the entry; nothing was recorded.",+ )+ parts = [f"Recorded 1 wrong question into the bank ({session_title})."]+ summary: dict[str, Any] = {+ "session_id": session_id,+ "question_id": item["question_id"],+ "source": "partner_chat",+ }+ name = (category or "").strip()[:MAX_CATEGORY_NAME]+ if name:+ entry = await store.find_notebook_entry(session_id, item["question_id"])+ entry_id = int(entry["id"]) if entry and entry.get("id") is not None else None+ if entry_id is None:+ parts.append("Could not file it into a category (entry not found after recording).")+ else:+ category_row, created = await _resolve_or_create_category(store, name)+ await store.link_entries_to_category([entry_id], int(category_row["id"]), link=True)+ parts.append(f"Filed under '{category_row['name']}'.")+ if created:+ parts.append("The category did not exist and was created.")+ summary["category"] = category_row["name"]+ parts.append("The learner sees it immediately under Learning Space → Question Bank.")+ return QuestionBankOutcome(ok=True, action="record", text=" ".join(parts), summary=summary)++async def run_question_bank(*,action: str = "overview",@@ -337,6 +478,12 @@ async def run_question_bank(entry_ids: Any = None,bookmarked: bool = True,limit: int = DEFAULT_LIST_LIMIT,+ question: str = "",+ user_answer: str = "",+ correct_answer: str = "",+ explanation: str = "",+ question_type: str = "",+ is_correct: bool = False,store: Any = None,) -> QuestionBankOutcome:"""Run one question-bank action. Never raises — errors come back typed."""@@ -366,6 +513,17 @@ async def run_question_bank(category=category,link=verb == "organize",)+ if verb == "record":+ return await _record(+ resolved,+ question=question,+ user_answer=user_answer,+ correct_answer=correct_answer,+ explanation=explanation,+ question_type=question_type,+ is_correct=is_correct,+ category=category,+ )return await _bookmark(resolved, entry_ids=entry_ids, bookmarked=bookmarked)except Exception as exc:logger.warning("question_bank action %s failed", verb, exc_info=True)diff --git a/tests/tools/test_question_bank_tool.py b/tests/tools/test_question_bank_tool.pyindex 16f54c2bd..c84c72ad2 100644--- a/tests/tools/test_question_bank_tool.py+++ b/tests/tools/test_question_bank_tool.py@@ -10,6 +10,7 @@ category when it is new.from __future__ import annotationsfrom pathlib import Path+from typing import Anyimport pytest@@ -172,3 +173,122 @@ async def test_mount_gate_follows_the_data(store: SQLiteSessionStore) -> None:assert store.has_question_bank_entries() is Falseawait _seed(store)assert store.has_question_bank_entries() is True+++# ── record (#1244): partner conversations file wrong questions ────────────+++class _FakePartnerContext:+ """Duck-typed stand-in for PartnerTurnContext (only the fields the tool+ reads via getattr: partner_id / actor_id / partner_name / shared_memory)."""++ def __init__(self, shared_memory: Any, partner_id: str = "p1") -> None:+ self.partner_id = partner_id+ self.actor_id = "user-42"+ self.partner_name = "Study Buddy"+ self.shared_memory = shared_memory+++async def test_record_files_a_partner_mistake_into_a_browsable_session(+ store: SQLiteSessionStore,+) -> None:+ outcome = await run_question_bank(+ action="record",+ question=" What is 7 × 8? ",+ user_answer="54",+ correct_answer="56",+ explanation="7×8 = 56, not 54 — the 7× row is easy to off-by-one.",+ category="Multiplication drills",+ store=store,+ )++ assert outcome.ok, outcome.error+ session_id = outcome.summary["session_id"]+ assert outcome.summary["source"] == "partner_chat"+ # The placeholder session exists so the entry is browsable, and the+ # mistake landed in it, labelled as coming from a partner conversation.+ stats = await store.question_bank_stats()+ assert stats["total"] == 1+ entry = await store.find_notebook_entry(session_id, outcome.summary["question_id"])+ assert entry is not None+ assert entry["source"] == "partner_chat"+ assert entry["question"] == "What is 7 × 8?"+ # The optional category was created and the entry filed into it.+ assert "Filed under 'Multiplication drills'" in outcome.text+++async def test_record_same_question_twice_updates_instead_of_duplicating(+ store: SQLiteSessionStore,+) -> None:+ first = await run_question_bank(action="record", question="What is 7 × 8?", store=store)+ again = await run_question_bank(+ action="record",+ question="WHAT is 7 × 8?", # different case/spacing, same question+ correct_answer="56",+ store=store,+ )++ assert first.ok and again.ok+ assert again.summary["question_id"] == first.summary["question_id"]+ assert (await store.question_bank_stats())["total"] == 1+++async def test_record_requires_the_question(store: SQLiteSessionStore) -> None:+ outcome = await run_question_bank(action="record", question=" ", store=store)+ assert not outcome.ok+ assert "`question` is required" in outcome.error+++async def test_record_routes_to_the_bank_the_family_browses(+ store: SQLiteSessionStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from deeptutor.services.path_service import PathService+ from deeptutor.services.session.sqlite_store import (+ get_sqlite_session_store_for,+ )++ learner_paths = PathService(workspace_root=tmp_path / "learner-scope")+ fake_context = _FakePartnerContext(shared_memory=learner_paths)+ monkeypatch.setattr(+ "deeptutor.services.partners.interaction.get_partner_turn_context",+ lambda: fake_context,+ )++ # No explicit store: inside a partner turn the tool must resolve the+ # learner-facing bank (the shared scope), not the partner's own.+ outcome = await run_question_bank(action="record", question="Define entropy.")++ assert outcome.ok, outcome.error+ partner_bank = get_sqlite_session_store_for(learner_paths)+ assert (await partner_bank.question_bank_stats())["total"] == 1+ # …and nothing leaked into the current (partner-scope) store.+ assert (await store.question_bank_stats())["total"] == 0+++async def test_partner_turns_mount_the_bank_even_when_it_is_empty(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from deeptutor.agents._shared.tool_composition import partner_can_record_questions+ from deeptutor.services.path_service import PathService++ assert partner_can_record_questions() is False++ fake_context = _FakePartnerContext(+ shared_memory=PathService(workspace_root=Path(tmp_path) / "scope")+ )+ monkeypatch.setattr(+ "deeptutor.services.partners.interaction.get_partner_turn_context",+ lambda: fake_context,+ )+ assert partner_can_record_questions() is True+++async def test_ensure_notebook_session_is_idempotent(store: SQLiteSessionStore) -> None:+ assert await store.ensure_notebook_session("partner-notebook:p1:admin", "T (Partner)") is True+ assert await store.ensure_notebook_session("partner-notebook:p1:admin", "T (Partner)") is Falsediff --git a/web/components/space/question-bank/BankToolbar.tsx b/web/components/space/question-bank/BankToolbar.tsxindex 14f473e46..68faaf553 100644--- a/web/components/space/question-bank/BankToolbar.tsx+++ b/web/components/space/question-bank/BankToolbar.tsx@@ -101,6 +101,7 @@ export default function BankToolbar({<option value="mastery_path">{t("Mastery Path")}</option><option value="immersive_reading">{t("Immersive Reading")}</option><option value="book">{t("Book")}</option>+ <option value="partner_chat">{t("Partner Chat")}</option></select><selectdiff --git a/web/components/space/question-bank/QuestionCard.tsx b/web/components/space/question-bank/QuestionCard.tsxindex 2435e8298..4006c83d1 100644--- a/web/components/space/question-bank/QuestionCard.tsx+++ b/web/components/space/question-bank/QuestionCard.tsx@@ -26,6 +26,7 @@ const SOURCE_LABELS: Record<NotebookEntry["source"], string> = {mastery_path: "Mastery Path",immersive_reading: "Immersive Reading",book: "Book",+ partner_chat: "Partner Chat",};const TREND_LABELS: Record<NotebookEntry["score_trend"], string> = {diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.tsindex a4d976883..d68b53a3e 100644--- a/web/lib/notebook-api.ts+++ b/web/lib/notebook-api.ts@@ -239,7 +239,8 @@ export type AssessmentSource =| "deep_question"| "mastery_path"| "immersive_reading"- | "book";+ | "book"+ | "partner_chat";export type ScoreTrend = "new" | "improved" | "declined" | "unchanged";diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 8a91940f4..4e19f59be 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3645,6 +3645,7 @@"All Sources": "All Sources","Deep Question": "Deep Question","Book": "Book",+ "Partner Chat": "Partner Chat","All Materials": "All Materials","Score Trend": "Score Trend","All Trends": "All Trends",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex d44038055..28898c59e 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3645,6 +3645,7 @@"All Sources": "全部来源","Deep Question": "深度提问","Book": "书籍",+ "Partner Chat": "伙伴对话","All Materials": "全部材料","Score Trend": "得分趋势","All Trends": "全部趋势",