DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor: land #713/#710/#707 on their proper seams
Bingxi Zhao (Frank)97632b71fe3f
diff --git a/deeptutor/agents/visualize/agents/analysis_agent.py b/deeptutor/agents/visualize/agents/analysis_agent.pyindex b379cf3cd..9e3b13c50 100644--- a/deeptutor/agents/visualize/agents/analysis_agent.py+++ b/deeptutor/agents/visualize/agents/analysis_agent.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom deeptutor.agents.base_agent import BaseAgentfrom deeptutor.core.context import Attachment+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..models import VisualizationAnalysisfrom ..utils import extract_json_object@@ -71,14 +72,22 @@ class AnalysisAgent(BaseAgent):user_prompt = user_template.format(**format_kwargs)- from deeptutor.services.llm import complete as llm_complete-- raw = await llm_complete(- prompt=user_prompt,+ # Blocking rather than streamed: nothing consumes the partial JSON, and+ # a reasoning model's <think> prelude never reaches the parser this way.+ raw = await self.call_llm(+ user_prompt=user_prompt,system_prompt=system_prompt,response_format={"type": "json_object"},- temperature=self.get_temperature(),- max_tokens=self.get_max_tokens(),+ stage="analyzing",+ attachments=attachments,+ trace_meta=build_trace_metadata(+ call_id=new_call_id("viz-analysis"),+ phase="analyzing",+ label="Visualization analysis",+ call_kind="viz_analysis",+ trace_role="analyze",+ trace_kind="llm_output",+ ),)result = VisualizationAnalysis.model_validate(extract_json_object(raw))if render_mode in ("svg", "chartjs", "mermaid", "html"):diff --git a/deeptutor/agents/visualize/agents/code_generator_agent.py b/deeptutor/agents/visualize/agents/code_generator_agent.pyindex fec9474fd..6012e9568 100644--- a/deeptutor/agents/visualize/agents/code_generator_agent.py+++ b/deeptutor/agents/visualize/agents/code_generator_agent.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport jsonfrom deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..models import VisualizationAnalysisfrom ..utils import extract_code_block@@ -57,13 +58,19 @@ class CodeGeneratorAgent(BaseAgent):analysis_json=json.dumps(analysis.model_dump(), ensure_ascii=False, indent=2),)- from deeptutor.services.llm import complete as llm_complete-- response = await llm_complete(- prompt=user_prompt,+ # Blocking rather than streamed: the fenced block is only usable whole.+ response = await self.call_llm(+ user_prompt=user_prompt,system_prompt=system_prompt,- temperature=self.get_temperature(),- max_tokens=self.get_max_tokens(),+ stage="generating",+ trace_meta=build_trace_metadata(+ call_id=new_call_id("viz-codegen"),+ phase="generating",+ label="Code generation",+ call_kind="viz_code_generation",+ trace_role="generate",+ trace_kind="llm_output",+ ),)if analysis.render_type == "svg":diff --git a/deeptutor/book/agents/spine_synthesizer.py b/deeptutor/book/agents/spine_synthesizer.pyindex a45451453..fd8619254 100644--- a/deeptutor/book/agents/spine_synthesizer.py+++ b/deeptutor/book/agents/spine_synthesizer.py@@ -254,16 +254,18 @@ class SpineSynthesizer(BaseAgent):stage: str,) -> dict[str, Any]:from ..blocks._language import language_directive- from deeptutor.services.llm import complete as llm_completesystem_prompt = system_prompt.rstrip() + language_directive(self.language)try:- raw = await llm_complete(- prompt=user_prompt,+ # Blocking rather than streamed: nothing consumes the partial JSON,+ # and a reasoning model's <think> prelude never reaches the parser+ # this way, so a truncated spine cannot collapse to one placeholder+ # chapter (#707).+ raw = await self.call_llm(+ user_prompt=user_prompt,system_prompt=system_prompt,response_format={"type": "json_object"},- temperature=self.get_temperature(),- max_tokens=self.get_max_tokens(),+ stage=stage,)except Exception as exc:logger.warning(f"SpineSynthesizer LLM call ({stage}) failed: {exc}")diff --git a/deeptutor/multi_user/paths.py b/deeptutor/multi_user/paths.pyindex d41a3bd4f..d29408f0c 100644--- a/deeptutor/multi_user/paths.py+++ b/deeptutor/multi_user/paths.py@@ -151,6 +151,30 @@ def get_current_path_service() -> PathService:return get_path_service_for_scope(user.scope)+def get_owner_path_service() -> PathService:+ """Resolve to the root of the human account that owns the current scope.++ A partner is a *synthetic* user, not a person: it has a workspace under+ ``data/partners/<id>`` but no account of its own, and that workspace is+ created by — and lives inside — the admin tree. Assets keyed to a real+ account rather than to a workspace (OAuth credentials, above all) must+ therefore resolve to the owner, or a partner turn would look for a login+ that can never exist there. Every other scope owns itself.++ Use this only for owner-keyed assets; workspace-keyed ones (rag, skills,+ notebooks, memory) belong to the partner and go through+ :func:`get_current_path_service`.+ """+ from deeptutor.services.partners.scope import is_partner_user_id++ from .context import get_current_user_or_none++ user = get_current_user_or_none()+ if user is not None and is_partner_user_id(user.id):+ return get_admin_path_service()+ return get_current_path_service()++@contextmanagerdef user_context(user: CurrentUser) -> Iterator[None]:from .context import reset_current_user, set_current_userdiff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.pyindex 93619d435..f34da93a5 100644--- a/deeptutor/runtime/launcher.py+++ b/deeptutor/runtime/launcher.py@@ -551,6 +551,28 @@ def _source_web_dir(home: Path) -> Path | None:return None+def _ensure_web_dependencies(source: Path, npm: str) -> None:+ """Install ``web/node_modules`` on a source checkout that has none.++ ``pip install -e ".[cli]"`` never touches npm, so a fresh clone would hand+ the dev server a missing ``next`` binary and die on Node's MODULE_NOT_FOUND+ (#709). Prefer ``npm ci`` — reproducible and faster — and fall back to+ ``npm install`` when the checkout has no lockfile. Output is left on the+ terminal so a failing install explains itself. No-op once installed, which+ keeps it cheap on the launcher's repeated resolve path.+ """+ if (source / "node_modules").exists():+ return+ action = "ci" if (source / "package-lock.json").exists() else "install"+ _log(f"web/node_modules not found — running `npm {action}` in {source} ...")+ result = subprocess.run([npm, action], cwd=source)+ if result.returncode != 0:+ raise SystemExit(+ f"`npm {action}` failed (exit {result.returncode}). "+ "Fix the error above, then retry `deeptutor start`."+ )++def _resolve_frontend(home: Path,frontend_port: int,@@ -578,21 +600,7 @@ def _resolve_frontend(raise SystemExit("npm not found. Source installs require Node.js/npm and `cd web && npm install`.")- if not (source / "node_modules").exists():- # node_modules is absent — install deps before starting the dev server.- # Use `npm ci` when a lockfile is present (reproducible, faster) and- # fall back to `npm install` otherwise.- has_lockfile = (source / "package-lock.json").exists()- install_cmd = [npm, "ci" if has_lockfile else "install"]- _log(- f"web/node_modules not found — running `{' '.join(install_cmd[1:])}` in {source} ..."- )- result = subprocess.run(install_cmd, cwd=source)- if result.returncode != 0:- raise SystemExit(- f"`npm {'ci' if has_lockfile else 'install'}` failed (exit {result.returncode}). "- "Fix the error above, then retry `deeptutor start`."- )+ _ensure_web_dependencies(source, npm)return FrontendRuntime("source", [npm, "run", "dev", "--", "--port", str(frontend_port)], source)diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.pyindex bf493d4ab..92e4047d2 100644--- a/deeptutor/services/codex_auth/service.py+++ b/deeptutor/services/codex_auth/service.py@@ -18,7 +18,6 @@ from deeptutor.services.config.model_catalog import (ModelCatalogService,get_model_catalog_service,)-from deeptutor.services.path_service import get_path_servicefrom .catalog import CodexModelCatalogfrom .constants import (@@ -621,20 +620,18 @@ _SERVICE_INSTANCES: dict[str, CodexOAuthService] = {}def _codex_user_root() -> Path:- """Anchor the credential store to the caller's own root.+ """Anchor the credential store to the account that owns the caller's scope.A Codex token is issued against one person's ChatGPT plan. Resolving otherusers to the administrator's root would run a whole deployment on a singlesubscription, so every account signs in for itself or does not use Codex.+ Owner resolution is what keeps that true while still letting a partner —+ a synthetic user with a workspace but no account — inherit the login of+ the person who owns it (#711)."""- from deeptutor.multi_user.context import get_current_user_or_none- from deeptutor.multi_user.paths import get_admin_path_service- from deeptutor.services.partners.scope import PARTNER_USER_PREFIX-- user = get_current_user_or_none()- if user is not None and user.id.startswith(PARTNER_USER_PREFIX):- return get_admin_path_service().get_user_root().resolve()- return get_path_service().get_user_root().resolve()+ from deeptutor.multi_user.paths import get_owner_path_service++ return get_owner_path_service().get_user_root().resolve()def get_codex_oauth_service() -> CodexOAuthService:diff --git a/deeptutor/services/partners/scope.py b/deeptutor/services/partners/scope.pyindex 2e162dadf..7bee1b941 100644--- a/deeptutor/services/partners/scope.py+++ b/deeptutor/services/partners/scope.py@@ -20,6 +20,11 @@ def partner_user_id(partner_id: str) -> str:return f"{PARTNER_USER_PREFIX}{partner_id}"+def is_partner_user_id(user_id: str) -> bool:+ """Whether *user_id* names a synthetic partner scope rather than a person."""+ return user_id.startswith(PARTNER_USER_PREFIX)++def partner_scope(partner_id: str) -> UserScope:workspace = get_partner_workspace(partner_id)return UserScope(@@ -39,4 +44,10 @@ def partner_user(partner_id: str, *, name: str = "") -> CurrentUser:)-__all__ = ["PARTNER_USER_PREFIX", "partner_scope", "partner_user", "partner_user_id"]+__all__ = [+ "PARTNER_USER_PREFIX",+ "is_partner_user_id",+ "partner_scope",+ "partner_user",+ "partner_user_id",+]diff --git a/tests/agents/visualize/test_agent_llm_calls.py b/tests/agents/visualize/test_agent_llm_calls.pynew file mode 100644index 000000000..1ce5c9766--- /dev/null+++ b/tests/agents/visualize/test_agent_llm_calls.py@@ -0,0 +1,85 @@+"""The visualize agents must call the LLM through their own agent seam.++Reaching for ``deeptutor.services.llm.complete`` directly silently drops what+``BaseAgent.call_llm`` carries: the image attachments the analysis stage was+given, the trace metadata the Activity panel renders, and the per-agent+api_key / base_url / binding routing (regression from #707).+"""++from __future__ import annotations++import json+from typing import Any++import pytest++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.visualize.agents.analysis_agent import AnalysisAgent+from deeptutor.agents.visualize.agents.code_generator_agent import CodeGeneratorAgent+from deeptutor.agents.visualize.models import VisualizationAnalysis+++def _record_call_llm(monkeypatch: pytest.MonkeyPatch, reply: str) -> dict[str, Any]:+ """Capture the kwargs an agent hands to ``BaseAgent.call_llm``."""+ recorded: dict[str, Any] = {}++ async def _call_llm(self: BaseAgent, **kwargs: Any) -> str:+ recorded.update(kwargs)+ return reply++ monkeypatch.setattr(BaseAgent, "call_llm", _call_llm)+ return recorded+++async def test_analysis_agent_forwards_attachments_and_trace(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ reply = json.dumps(+ {+ "render_type": "svg",+ "description": "a bar chart",+ "data_description": "two series",+ "chart_type": "bar",+ "visual_elements": ["bars"],+ "rationale": "simple comparison",+ }+ )+ recorded = _record_call_llm(monkeypatch, reply)+ attachments = [object()]++ await AnalysisAgent().process(+ user_input="chart our revenue",+ history_context="",+ render_mode="svg",+ attachments=attachments, # type: ignore[arg-type]+ )++ assert recorded["attachments"] is attachments+ assert recorded["stage"] == "analyzing"+ assert recorded["trace_meta"]["call_kind"] == "viz_analysis"+ assert recorded["response_format"] == {"type": "json_object"}+++async def test_code_generator_agent_emits_its_trace(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ recorded = _record_call_llm(monkeypatch, "```svg\n<svg/>\n```")+ analysis = VisualizationAnalysis(+ render_type="svg",+ description="a bar chart",+ data_description="two series",+ chart_type="bar",+ visual_elements=["bars"],+ rationale="simple comparison",+ )++ await CodeGeneratorAgent().process(+ user_input="chart our revenue",+ history_context="",+ analysis=analysis,+ )++ assert recorded["stage"] == "generating"+ assert recorded["trace_meta"]["call_kind"] == "viz_code_generation"diff --git a/tests/book/test_spine_synthesizer_llm_call.py b/tests/book/test_spine_synthesizer_llm_call.pynew file mode 100644index 000000000..dc8618ea6--- /dev/null+++ b/tests/book/test_spine_synthesizer_llm_call.py@@ -0,0 +1,62 @@+"""The spine synthesizer must reach the LLM through its own agent seam.++``_call_json`` is blocking on purpose — nothing consumes a partial spine, and a+reasoning model's ``<think>`` prelude never reaches the parser this way (#707).+But it has to stay on ``BaseAgent.call_llm``: calling the factory directly drops+the trace event the Book Activity panel renders and the per-agent+api_key / base_url / binding routing.+"""++from __future__ import annotations++import json+from typing import Any++import pytest++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.book.agents.spine_synthesizer import SpineSynthesizer+++async def test_call_json_goes_through_call_llm_with_its_stage(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ recorded: dict[str, Any] = {}++ async def _call_llm(self: BaseAgent, **kwargs: Any) -> str:+ recorded.update(kwargs)+ return json.dumps({"chapters": [{"title": "Vectors"}]})++ monkeypatch.setattr(BaseAgent, "call_llm", _call_llm)++ payload = await SpineSynthesizer(language="ja")._call_json(+ system_prompt="Design a spine.",+ user_prompt="About linear algebra.",+ stage="spine_draft",+ )++ assert payload == {"chapters": [{"title": "Vectors"}]}+ assert recorded["stage"] == "spine_draft"+ assert recorded["response_format"] == {"type": "json_object"}+ # The language directive rides on the system prompt, so a non-en/zh book+ # still tells the model which language to write in (#712).+ assert "日本語" in recorded["system_prompt"]+++async def test_call_json_returns_an_empty_payload_when_the_call_fails(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def _boom(self: BaseAgent, **_kwargs: Any) -> str:+ raise RuntimeError("provider down")++ monkeypatch.setattr(BaseAgent, "call_llm", _boom)++ payload = await SpineSynthesizer()._call_json(+ system_prompt="Design a spine.",+ user_prompt="About linear algebra.",+ stage="spine_draft",+ )++ assert payload == {}diff --git a/tests/multi_user/test_owner_path_service.py b/tests/multi_user/test_owner_path_service.pynew file mode 100644index 000000000..5035f6a0c--- /dev/null+++ b/tests/multi_user/test_owner_path_service.py@@ -0,0 +1,51 @@+"""Owner resolution for scopes that are not people.++A partner runs as a synthetic user: it owns a workspace but never an account.+Assets keyed to an account — OAuth credentials above all — must therefore+resolve to the human who owns the partner (#711), while workspace-keyed assets+(rag, skills, notebooks, memory) stay with the partner itself.+"""++from __future__ import annotations++from deeptutor.multi_user.context import reset_current_user, set_current_user+from deeptutor.multi_user.paths import (+ get_admin_path_service,+ get_current_path_service,+ get_owner_path_service,+)+from deeptutor.services.partners.scope import (+ is_partner_user_id,+ partner_user,+ partner_user_id,+)+++def test_is_partner_user_id_separates_synthetic_scopes_from_people() -> None:+ assert is_partner_user_id(partner_user_id("ada"))+ assert not is_partner_user_id("u_alice")+++def test_a_person_owns_themselves(mu_isolated_root, as_user) -> None:+ with as_user("u_alice"):+ assert get_owner_path_service().get_user_root() == (+ get_current_path_service().get_user_root()+ )+++def test_partner_scope_resolves_to_its_owner(mu_isolated_root) -> None:+ """The partner's own root has no credentials; the owner's does."""+ token = set_current_user(partner_user("ada"))+ try:+ partner_root = get_current_path_service().get_user_root()+ owner_root = get_owner_path_service().get_user_root()+ finally:+ reset_current_user(token)++ assert partner_root == mu_isolated_root / "data" / "partners" / "ada" / "workspace" / "user"+ assert owner_root == get_admin_path_service().get_user_root()+ assert owner_root != partner_root+++def test_no_active_scope_falls_back_to_the_current_path_service(mu_isolated_root) -> None:+ assert get_owner_path_service().get_user_root() == (get_current_path_service().get_user_root())diff --git a/tests/runtime/test_launcher.py b/tests/runtime/test_launcher.pyindex 1d5a1161d..16f7d5343 100644--- a/tests/runtime/test_launcher.py+++ b/tests/runtime/test_launcher.py@@ -215,3 +215,80 @@ def test_relax_console_encoding_replaces_unencodable_output() -> None:def test_relax_console_encoding_tolerates_odd_streams() -> None:"""Redirected / already-detached streams must not break startup."""launcher._relax_console_encoding((object(), _RecordingStream(raises=ValueError("detached"))))+++class _CompletedProcess:+ def __init__(self, returncode: int) -> None:+ self.returncode = returncode+++def test_ensure_web_dependencies_runs_npm_ci_when_a_lockfile_exists(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A fresh source clone has no ``web/node_modules`` and used to die on Node's+ MODULE_NOT_FOUND before the dev server ever started (issue #709)."""+ source = tmp_path / "web"+ source.mkdir()+ (source / "package-lock.json").write_text("{}", encoding="utf-8")+ calls: list[tuple[list[str], Path]] = []++ def _run(cmd, cwd, **_kwargs):+ calls.append((list(cmd), Path(cwd)))+ (source / "node_modules").mkdir()+ return _CompletedProcess(0)++ monkeypatch.setattr(launcher.subprocess, "run", _run)++ launcher._ensure_web_dependencies(source, "npm")++ assert calls == [(["npm", "ci"], source)]+++def test_ensure_web_dependencies_falls_back_to_npm_install_without_a_lockfile(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ source = tmp_path / "web"+ source.mkdir()+ calls: list[list[str]] = []+ monkeypatch.setattr(+ launcher.subprocess,+ "run",+ lambda cmd, cwd, **_kw: (calls.append(list(cmd)), _CompletedProcess(0))[1],+ )++ launcher._ensure_web_dependencies(source, "npm")++ assert calls == [["npm", "install"]]+++def test_ensure_web_dependencies_is_a_no_op_once_installed(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The launcher resolves the frontend more than once per start."""+ source = tmp_path / "web"+ (source / "node_modules").mkdir(parents=True)++ def _boom(*_args, **_kwargs):+ raise AssertionError("npm must not run when node_modules is present")++ monkeypatch.setattr(launcher.subprocess, "run", _boom)++ launcher._ensure_web_dependencies(source, "npm")+++def test_ensure_web_dependencies_surfaces_a_failed_install(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ source = tmp_path / "web"+ source.mkdir()+ (source / "package-lock.json").write_text("{}", encoding="utf-8")+ monkeypatch.setattr(launcher.subprocess, "run", lambda *_a, **_kw: _CompletedProcess(1))++ with pytest.raises(SystemExit) as excinfo:+ launcher._ensure_web_dependencies(source, "npm")++ assert "npm ci" in str(excinfo.value)diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.pyindex 35f6526e5..4f8956fd6 100644--- a/tests/services/codex_auth/test_service.py+++ b/tests/services/codex_auth/test_service.py@@ -38,18 +38,47 @@ def test_each_user_gets_their_own_codex_credential_root(Resolving other accounts to the administrator's root would run an entiredeployment on a single subscription."""+ from deeptutor.multi_user import paths as paths_module+roots = {"admin": tmp_path / "admin-user", "learner": tmp_path / "regular-user"}signed_in = {"who": "admin"}monkeypatch.setattr(- service_module,- "get_path_service",+ paths_module,+ "get_owner_path_service",lambda: type("Paths", (), {"get_user_root": lambda self: roots[signed_in["who"]]})(),)assert service_module._codex_user_root() == roots["admin"]signed_in["who"] = "learner"assert service_module._codex_user_root() == roots["learner"]+ # Who owns a scope is decided by get_owner_path_service, not here: codex_auth+ # must never reach for the admin root — or learn what a partner is — itself.assert not hasattr(service_module, "get_admin_path_service")+ assert not hasattr(service_module, "PARTNER_USER_PREFIX")+++def test_partner_turn_inherits_its_owner_codex_login(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """A partner has a workspace but no account, so it borrows its owner's token.++ Before #711 the credential store followed the partner scope to+ ``data/partners/<id>/workspace/user``, found nothing, and failed in 0s.+ """+ from deeptutor.multi_user import paths as paths_module+ from deeptutor.multi_user.context import reset_current_user, set_current_user+ from deeptutor.services.partners.scope import partner_user++ admin_root = (tmp_path / "data").resolve()+ monkeypatch.setattr(paths_module, "ADMIN_WORKSPACE_ROOT", admin_root)+ monkeypatch.setattr(paths_module, "_path_services", {})++ token = set_current_user(partner_user("ada"))+ try:+ assert service_module._codex_user_root() == admin_root / "user"+ finally:+ reset_current_user(token)def _model(