Skip to content

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

fix(ci): align preview fixtures and formatting with current contracts

Bingxi Zhao (Frank)9d822fcdf015
diff --git a/deeptutor/agents/loop/loop_host.py b/deeptutor/agents/loop/loop_host.py
index 1249d18da..8c220e56f 100644
--- a/deeptutor/agents/loop/loop_host.py
+++ b/deeptutor/agents/loop/loop_host.py
@@ -96,7 +96,8 @@ class AgentLoopHost:
return {"available": False, "rejected": False}
instruction, names = recovery
self.recovery_schemas = [
- schema for schema in self.loop.tool_schemas or []
+ schema
+ for schema in self.loop.tool_schemas or []
if (schema.get("function") or {}).get("name") in names
]
self.recovery_tools = frozenset(
diff --git a/deeptutor/agents/loop/python_scheduler.py b/deeptutor/agents/loop/python_scheduler.py
index 2957d77e6..b1849f500 100644
--- a/deeptutor/agents/loop/python_scheduler.py
+++ b/deeptutor/agents/loop/python_scheduler.py
@@ -53,8 +53,10 @@ async def run_loop(host: Any, config: dict[str, int]) -> dict[str, int]:
try:
result = await invoke("call_round", settling=settling, first=state["rounds"] == 0)
except Exception as exc:
- if isinstance(exc, CapabilityPrerequisiteError) or state["rounds"] == 0 or (
- isinstance(exc, LLMProviderTransportError) and exc.partial_response
+ if (
+ isinstance(exc, CapabilityPrerequisiteError)
+ or state["rounds"] == 0
+ or (isinstance(exc, LLMProviderTransportError) and exc.partial_response)
):
raise
return await force_finish("error", str(exc))
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 91aa0ae18..8b7579bc5 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -526,7 +526,8 @@ def _install_request_workspace(request) -> None:
# Management/migration requests acquire their own exclusive lease.
task_board_request = path == "/api/task-board" or path.startswith("/api/task-board/")
if getattr(request, "method", None) is not None and (
- not management or (task_board_request and path != "/api/task-board/events")
+ not management
+ or (task_board_request and path != "/api/task-board/events")
or (path.startswith("/api/calendar/") and path != "/api/calendar/stream")
):
from deeptutor.services.workspace.activity import acquire_activity
diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.py
index 0f1b1982f..98dc51567 100644
--- a/deeptutor/api/routers/partners.py
+++ b/deeptutor/api/routers/partners.py
@@ -681,9 +681,19 @@ async def partner_navigation():
from deeptutor.services.partner_groups import get_partner_group_manager
partners = [
- {key: row.get(key) for key in (
- "partner_id", "name", "description", "emoji", "color", "avatar", "can_manage", "running",
- )}
+ {
+ key: row.get(key)
+ for key in (
+ "partner_id",
+ "name",
+ "description",
+ "emoji",
+ "color",
+ "avatar",
+ "can_manage",
+ "running",
+ )
+ }
for row in visible_partners()
]
group_manager = get_partner_group_manager()
@@ -697,24 +707,31 @@ async def partner_navigation():
try:
rows = (
manager.session_store(owner_id).list_sessions()
- if kind == "partner" else group_manager.list_sessions(owner_id)
+ if kind == "partner"
+ else group_manager.list_sessions(owner_id)
)
for row in rows:
if row.get("archived"):
continue
- sessions.append(NavigationSession(
- kind=kind,
- owner_id=owner_id,
- owner_name=owner["name"],
- session_key=row["session_key"],
- title=str(row.get("title") or row.get("last_message") or "")[:160],
- updated_at=_navigation_timestamp(row.get("updated_at")),
- ))
+ sessions.append(
+ NavigationSession(
+ kind=kind,
+ owner_id=owner_id,
+ owner_name=owner["name"],
+ session_key=row["session_key"],
+ title=str(row.get("title") or row.get("last_message") or "")[:160],
+ updated_at=_navigation_timestamp(row.get("updated_at")),
+ )
+ )
except Exception:
- logger.warning("Partner navigation unavailable: %s/%s", kind, owner_id, exc_info=True)
+ logger.warning(
+ "Partner navigation unavailable: %s/%s", kind, owner_id, exc_info=True
+ )
unavailable.append(f"{kind}:{owner_id}")
sessions.sort(key=lambda row: (-row.updated_at, row.kind, row.owner_id, row.session_key))
- return PartnerNavigation(partners=partners, groups=groups, sessions=sessions, unavailable=unavailable)
+ return PartnerNavigation(
+ partners=partners, groups=groups, sessions=sessions, unavailable=unavailable
+ )
@router.get("/consultation-session")
diff --git a/deeptutor/api/routers/practice.py b/deeptutor/api/routers/practice.py
index 20b2ee2fb..e57fcde5c 100644
--- a/deeptutor/api/routers/practice.py
+++ b/deeptutor/api/routers/practice.py
@@ -143,9 +143,7 @@ async def practice_analytics(timezone: str = "UTC", days: int = 30):
raise HTTPException(422, "Days must be 7, 30, or 90")
store = get_sqlite_session_store()
try:
- return await asyncio.to_thread(
- PracticeStore(store.db_path).analytics, timezone, days
- )
+ return await asyncio.to_thread(PracticeStore(store.db_path).analytics, timezone, days)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
diff --git a/deeptutor/api/routers/question_notebook.py b/deeptutor/api/routers/question_notebook.py
index ee9491d9d..8984a3100 100644
--- a/deeptutor/api/routers/question_notebook.py
+++ b/deeptutor/api/routers/question_notebook.py
@@ -494,22 +494,17 @@ async def remove_entry_from_category(entry_id: int, category_id: int):
@router.get("/stats", response_model=QuestionBankStats)
-async def question_bank_stats(
-) -> QuestionBankStats:
+async def question_bank_stats() -> QuestionBankStats:
"""Counts behind the filter chips; also the agent's one-call overview."""
store = get_sqlite_session_store()
return QuestionBankStats(**await store.question_bank_stats())
@router.get("/materials", response_model=list[QuestionBankMaterial])
-async def list_question_bank_materials(
-) -> list[QuestionBankMaterial]:
+async def list_question_bank_materials() -> list[QuestionBankMaterial]:
"""Materials represented in the unified review history."""
store = get_sqlite_session_store()
- return [
- QuestionBankMaterial(**item)
- for item in await store.list_question_bank_materials()
- ]
+ return [QuestionBankMaterial(**item) for item in await store.list_question_bank_materials()]
# ── Category CRUD ────────────────────────────────────────────────
diff --git a/deeptutor/services/practice/analytics.py b/deeptutor/services/practice/analytics.py
index e4ce168f3..438236883 100644
--- a/deeptutor/services/practice/analytics.py
+++ b/deeptutor/services/practice/analytics.py
@@ -7,9 +7,7 @@ from zoneinfo import ZoneInfo
from .scheduler import day_bounds
-def analytics(
- conn: sqlite3.Connection, timezone: str, days: int, now: float
-) -> dict:
+def analytics(conn: sqlite3.Connection, timezone: str, days: int, now: float) -> dict:
if days not in {7, 30, 90}:
raise ValueError("Choose 7, 30 or 90 days")
day_bounds(timezone, now)
diff --git a/deeptutor/services/practice/storage.py b/deeptutor/services/practice/storage.py
index 04e63c47f..049d58d90 100644
--- a/deeptutor/services/practice/storage.py
+++ b/deeptutor/services/practice/storage.py
@@ -303,9 +303,7 @@ class PracticeStore:
)
return outcome
- def stage_import(
- self, filename: str, target: str, questions: list[dict]
- ) -> str:
+ def stage_import(self, filename: str, target: str, questions: list[dict]) -> str:
token, now = uuid.uuid4().hex, time.time()
with self.connect() as conn:
conn.execute(
diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.py
index 396d097da..f53e1a6d2 100644
--- a/deeptutor/services/session/_turn_runtime_shared.py
+++ b/deeptutor/services/session/_turn_runtime_shared.py
@@ -1413,6 +1413,7 @@ class _TurnExecution:
# Compatibility for saved requests and clients using passage-based tutoring.
SELECTION_TUTOR_MAX_CHARS = 12_000
+
def _extract_selection_tutor_context(
config: dict[str, Any] | None,
) -> dict[str, Any] | None:
@@ -1470,6 +1471,7 @@ def _extract_selection_tutor_context(
context["source_message_role"] = source_message_role
return context
+
def _selection_source_excerpt(
source_text: str,
selected_text: str,
@@ -1500,6 +1502,7 @@ def _selection_source_excerpt(
excerpt += "\n[later content omitted]"
return excerpt
+
def _selected_latex_body(selected: str) -> str | None:
"""Return the body of a complete Markdown math selection, if any."""
match = re.fullmatch(r"\$\$(.+?)\$\$|\$(.+?)\$", selected, flags=re.DOTALL)
@@ -1514,6 +1517,7 @@ def _selected_latex_body(selected: str) -> str | None:
return None
return body
+
def _selection_start(source: str, selected: str) -> int:
"""Find an exact selection, or its equivalent LaTeX body, in source text."""
start = source.find(selected) if selected else -1
@@ -1526,6 +1530,7 @@ def _selection_start(source: str, selected: str) -> int:
match = re.search(pattern, source, flags=re.DOTALL)
return match.start() if match else -1
+
def _latex_selection_is_grounded(source: str, selected: str) -> bool:
"""Whether selected KaTeX LaTeX has an equivalent body in the source.
@@ -1541,6 +1546,7 @@ def _latex_selection_is_grounded(source: str, selected: str) -> bool:
normalized_source = " ".join(source.split())
return body in normalized_source
+
def _selection_is_grounded(source_text: str, selected_text: str) -> bool:
"""Whether the claimed selection occurs in its containing message."""
source = str(source_text or "")
@@ -1558,6 +1564,7 @@ def _selection_is_grounded(source_text: str, selected_text: str) -> bool:
return True
return _latex_selection_is_grounded(normalized_source, normalized_selected)
+
async def _resolve_selection_tutor_context(
store: Any,
context: dict[str, Any],
@@ -1623,6 +1630,7 @@ async def _resolve_selection_tutor_context(
)
return resolved
+
def _format_selection_tutor_context(context: dict[str, Any], language: str = "en") -> str:
if context.get("scope") == "conversation":
return _format_side_chat_context(context, language=language)
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 5b4b95338..d39839348 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -4183,14 +4183,18 @@ class SQLiteSessionStore:
Uses the same recycle predicate as the Question Bank. No new schema or
migration: old entry IDs remain the IDs used by practice and review.
"""
+
def read() -> list[dict[str, Any]]:
with self._connect() as conn:
- return [dict(row) for row in conn.execute(
- "SELECT id, substr(question, 1, 160) AS question, created_at, updated_at "
- "FROM notebook_entries WHERE "
- + _NOT_RECYCLED_ENTRY_SQL.format(entries="notebook_entries")
- + " ORDER BY updated_at DESC, id DESC"
- ).fetchall()]
+ return [
+ dict(row)
+ for row in conn.execute(
+ "SELECT id, substr(question, 1, 160) AS question, created_at, updated_at "
+ "FROM notebook_entries WHERE "
+ + _NOT_RECYCLED_ENTRY_SQL.format(entries="notebook_entries")
+ + " ORDER BY updated_at DESC, id DESC"
+ ).fetchall()
+ ]
return await self._run(read)
diff --git a/deeptutor/services/session/turns/request_preparer.py b/deeptutor/services/session/turns/request_preparer.py
index ed94a4d37..71bef7a9d 100644
--- a/deeptutor/services/session/turns/request_preparer.py
+++ b/deeptutor/services/session/turns/request_preparer.py
@@ -84,6 +84,7 @@ _REPLAY_SNAPSHOT_FIELDS: dict[str, str] = {
"auto_route": "autoRoute",
}
+
def _tutor_thread_preferences(context: dict[str, Any]) -> dict[str, Any]:
if context.get("selected_text"):
return {
diff --git a/deeptutor/services/task_board.py b/deeptutor/services/task_board.py
index f9c2e8976..aa05467ca 100644
--- a/deeptutor/services/task_board.py
+++ b/deeptutor/services/task_board.py
@@ -232,7 +232,15 @@ class TaskBoardStore:
connection.execute("BEGIN IMMEDIATE")
connection.execute(
"INSERT INTO cards (id,title,note,status,archived,created_at,updated_at,workspace_id,due_date) VALUES (?,?,?,'todo',0,?,?,?,?)",
- (uuid4().hex, payload.title, payload.note, now, now, workspace_id, payload.due_date),
+ (
+ uuid4().hex,
+ payload.title,
+ payload.note,
+ now,
+ now,
+ workspace_id,
+ payload.due_date,
+ ),
)
self._changed(connection)
return self._snapshot(connection)
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index d34f768ea..0dd7128c1 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -1650,7 +1650,10 @@ class SaveFavoriteTool(_PromptHintsMixin, BaseTool):
from deeptutor.tools.write_note import write_note
if kwargs.get("mode") == "edit" and kwargs.get("content"):
- return ToolResult(content="Favorites preserve original content; add to a notebook page to edit.", success=False)
+ return ToolResult(
+ content="Favorites preserve original content; add to a notebook page to edit.",
+ success=False,
+ )
outcome = write_note(
mode=str(kwargs.get("mode") or ""),
diff --git a/tests/agents/chat/test_context_budget.py b/tests/agents/chat/test_context_budget.py
index 00f1ce60c..0eeb8f612 100644
--- a/tests/agents/chat/test_context_budget.py
+++ b/tests/agents/chat/test_context_budget.py
@@ -23,7 +23,7 @@ from deeptutor.agents.loop.context_budget import (
resolve_window_info,
)
from deeptutor.capabilities import PromptBlock
-from deeptutor.core.context import UnifiedContext
+from deeptutor.core.context import TurnRuntimeContext, UnifiedContext, WorkspaceRuntimeContext
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.tool_protocol import ToolResult
from deeptutor.runtime.stream_bus import StreamBus
@@ -456,6 +456,7 @@ async def test_turn_result_carries_the_context_budget(monkeypatch: pytest.Monkey
user_message="Explain gradient descent",
language="en",
metadata={"turn_id": "t1"},
+ runtime=TurnRuntimeContext(workspace=WorkspaceRuntimeContext()),
),
bus,
)
@@ -537,6 +538,7 @@ async def test_forced_finish_still_reports_the_tools_the_turn_carried(
user_message="Explain gradient descent",
language="en",
metadata={"turn_id": "t2"},
+ runtime=TurnRuntimeContext(workspace=WorkspaceRuntimeContext()),
),
bus,
)
diff --git a/tests/multi_user/test_learning_policy_http.py b/tests/multi_user/test_learning_policy_http.py
index 684f786f3..c8faa90be 100644
--- a/tests/multi_user/test_learning_policy_http.py
+++ b/tests/multi_user/test_learning_policy_http.py
@@ -224,7 +224,9 @@ def test_dashboard_learning_library_follows_the_policy(learner_client, as_user):
assert "reading surface" in denied.json()["detail"]
-def test_learning_navigation_index_filters_sources_without_opening_dashboard(learner_client, as_user):
+def test_learning_navigation_index_filters_sources_without_opening_dashboard(
+ learner_client, as_user
+):
client, learner, current_user, tmp_path = learner_client
with as_user(current_user.id, username="student"):
material = _seed_material(tmp_path, "navigation.txt", "Assigned reading.")
diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.py
index 89df659e8..90d04cfad 100644
--- a/tests/services/session/test_turn_runtime_subscribe.py
+++ b/tests/services/session/test_turn_runtime_subscribe.py
@@ -445,10 +445,6 @@ async def test_start_turn_preserves_selection_tutor_runtime_context(
assert resolved["source_message_text"] == source_text
-
-
-
-
@pytest.mark.asyncio
async def test_side_chat_starts_from_the_parent_alone(
monkeypatch: pytest.MonkeyPatch, tmp_path