DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(mastery): restore Skills picker and workspace persona presets
Gao-Chenkaif272234bed9d
diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.pyindex 0f1fd56dc..2b82fa521 100644--- a/deeptutor/api/routers/partners.py+++ b/deeptutor/api/routers/partners.py@@ -531,11 +531,10 @@ def _load_persona_markdown(name: str) -> str:except Exception:passtry:- if not get_current_user().is_admin:- admin_service = PersonaService(- root=get_admin_path_service().get_workspace_dir() / "personas"- )- return strip_frontmatter(admin_service.get_detail(name).content)+ admin_service = PersonaService(+ root=get_admin_path_service().get_workspace_dir() / "personas"+ )+ return strip_frontmatter(admin_service.get_detail(name).content)except Exception:passreturn ""@@ -609,13 +608,12 @@ async def soul_sources():except Exception:logger.warning("Failed to list user personas", exc_info=True)try:- if not get_current_user().is_admin:- admin_service = PersonaService(- root=get_admin_path_service().get_workspace_dir() / "personas"- )- for info in admin_service.list_personas():- if info.name not in seen:- personas.append(_persona_entry(admin_service, info))+ admin_service = PersonaService(+ root=get_admin_path_service().get_workspace_dir() / "personas"+ )+ for info in admin_service.list_personas():+ if info.name not in seen:+ personas.append(_persona_entry(admin_service, info))except Exception:logger.warning("Failed to list admin personas", exc_info=True)diff --git a/deeptutor/api/routers/personas.py b/deeptutor/api/routers/personas.pyindex 27d9e46e4..3f25c9bb9 100644--- a/deeptutor/api/routers/personas.py+++ b/deeptutor/api/routers/personas.py@@ -19,7 +19,6 @@ from __future__ import annotationsfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from deeptutor.multi_user.context import get_current_userfrom deeptutor.multi_user.paths import get_admin_path_servicefrom deeptutor.services.i18n import tfrom deeptutor.services.persona import (@@ -49,13 +48,13 @@ def _admin_persona_service() -> PersonaService:return PersonaService(root=get_admin_path_service().get_workspace_dir() / "personas")[email protected]("/personas")-async def list_personas() -> dict[str, list[dict[str, object]]]:- service = get_persona_service()- own = [info.to_dict() for info in service.list_personas()]- user = get_current_user()- if user.is_admin:- return {"personas": own}+def _visible_personas() -> list[dict[str, object]]:+ """Workspace-local personas plus unshadowed admin presets.++ Isolation is preserved: CRUD still writes only to the active workspace.+ Admin-authored presets are a read-only overlay for every role.+ """+ own = [info.to_dict() for info in get_persona_service().list_personas()]own_names = {item["name"] for item in own}merged = list(own)for preset in _admin_persona_service().list_personas():@@ -64,7 +63,12 @@ async def list_personas() -> dict[str, list[dict[str, object]]]:entry = preset.to_dict()entry.update({"source": "admin", "read_only": True})merged.append(entry)- return {"personas": merged}+ return merged++[email protected]("/personas")+async def list_personas() -> dict[str, list[dict[str, object]]]:+ return {"personas": _visible_personas()}@router.get("/personas/{name}")@@ -77,14 +81,14 @@ async def get_persona(name: str) -> dict[str, object]:except InvalidPersonaNameError as exc:raise HTTPException(status_code=400, detail=str(exc))- user = get_current_user()- if not user.is_admin:- try:- detail = _admin_persona_service().get_detail(name).to_dict()- detail.update({"source": "admin", "read_only": True})- return detail- except (PersonaNotFoundError, InvalidPersonaNameError):- pass+ try:+ detail = _admin_persona_service().get_detail(name).to_dict()+ detail.update({"source": "admin", "read_only": True})+ return detail+ except PersonaNotFoundError:+ pass+ except InvalidPersonaNameError as exc:+ raise HTTPException(status_code=400, detail=str(exc))raise HTTPException(status_code=404, detail=t("api.persona_not_found", name=name))diff --git a/deeptutor/services/persona/__init__.py b/deeptutor/services/persona/__init__.pyindex 1ec50a170..ee2856367 100644--- a/deeptutor/services/persona/__init__.py+++ b/deeptutor/services/persona/__init__.py@@ -10,6 +10,7 @@ from .service import (PersonaNotFoundError,PersonaService,get_persona_service,+ load_visible_for_context,)__all__ = [@@ -22,4 +23,5 @@ __all__ = ["PersonaNotFoundError","PersonaService","get_persona_service",+ "load_visible_for_context",]diff --git a/deeptutor/services/persona/service.py b/deeptutor/services/persona/service.pyindex 7c875dd88..1c774bc7d 100644--- a/deeptutor/services/persona/service.py+++ b/deeptutor/services/persona/service.py@@ -359,6 +359,32 @@ def get_persona_service() -> PersonaService:return _instances[key]+def load_visible_for_context(+ name: str,+ *,+ workspace: PersonaService | None = None,+ admin: PersonaService | None = None,+) -> str:+ """Render a persona from the active workspace, then admin presets.++ Workspace-local files stay isolated. Admin presets are a read-only overlay+ visible to every role — including an admin in an explicit workspace whose+ own ``personas/`` directory is empty.+ """+ if not name:+ return ""+ text = (workspace or get_persona_service()).load_for_context(name)+ if text:+ return text+ if admin is None:+ from deeptutor.multi_user.paths import get_admin_path_service++ admin = PersonaService(+ root=get_admin_path_service().get_workspace_dir() / "personas"+ )+ return admin.load_for_context(name)++__all__ = ["InvalidPersonaNameError","LEGACY_PERSONA_SKILLS",@@ -369,4 +395,5 @@ __all__ = ["PersonaNotFoundError","PersonaService","get_persona_service",+ "load_visible_for_context",]diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex 4548ea41c..e6d8d3db8 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -499,12 +499,14 @@ class TurnExecutor:# Persona: at most one behaviour preset per turn, eagerly# injected (a persona must shape the voice from the first- # token). Resolution: the user's own workspace first; non-admin- # users fall back to admin-authored presets (personas carry no+ # token). Resolution: the user's own workspace first, then+ # admin-authored presets for every role (personas carry no# privileged workflow, so no grant gate applies).from deeptutor.multi_user.context import get_current_user- from deeptutor.multi_user.paths import get_admin_path_service- from deeptutor.services.persona import PersonaService, get_persona_service+ from deeptutor.services.persona import (+ get_persona_service,+ load_visible_for_context,+ )current_user = get_current_user()learner_profile_prompt = ""@@ -516,13 +518,14 @@ class TurnExecutor:if account and str(account[1].get("preset") or "standard") == "learner":learner_profile_prompt = prompt_block(account[1].get("learner_profile"))requested_persona = str(payload.get("persona") or "").strip()- persona_context = ""- if requested_persona:- persona_context = get_persona_service().load_for_context(requested_persona)- if not persona_context and not current_user.is_admin:- persona_context = PersonaService(- root=get_admin_path_service().get_workspace_dir() / "personas"- ).load_for_context(requested_persona)+ persona_context = (+ load_visible_for_context(+ requested_persona,+ workspace=get_persona_service(),+ )+ if requested_persona+ else ""+ )active_persona = requested_persona if persona_context else ""from deeptutor.services.skill.runtime import skill_manifestdiff --git a/tests/api/test_personas_router.py b/tests/api/test_personas_router.pynew file mode 100644index 000000000..e846e119c--- /dev/null+++ b/tests/api/test_personas_router.py@@ -0,0 +1,88 @@+"""GET /api/personas merges admin presets for every role (#1534)."""++from __future__ import annotations++import importlib+from pathlib import Path++import pytest++from deeptutor.services.persona.service import PersonaService++try:+ from fastapi import FastAPI+ from fastapi.testclient import TestClient+except Exception: # pragma: no cover - optional in the CLI-only package+ FastAPI = None+ TestClient = None++pytestmark = pytest.mark.skipif(+ FastAPI is None or TestClient is None, reason="fastapi not installed"+)+++def personas_api(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ module = importlib.import_module("deeptutor.api.routers.personas")+ workspace = PersonaService(root=tmp_path / "workspace" / "personas")+ admin = PersonaService(root=tmp_path / "admin" / "personas")+ admin.seed_presets()+ monkeypatch.setattr(module, "get_persona_service", lambda: workspace)+ monkeypatch.setattr(module, "_admin_persona_service", lambda: admin)++ app = FastAPI()+ app.include_router(module.router, prefix="/api")+ return TestClient(app), workspace, admin+++def _by_name(body: dict) -> dict[str, dict]:+ return {row["name"]: row for row in body["personas"]}+++def test_empty_workspace_lists_admin_presets(personas_api) -> None:+ # The #1534 shape: an explicit workspace has no local PERSONA.md files,+ # but the account still has the bundled presets. Admins used to skip the+ # merge and see only Default.+ client, workspace, _admin = personas_api+ assert workspace.list_personas() == []++ body = client.get("/api/personas").json()+ names = _by_name(body)+ assert {"peer", "teacher", "research-assistant"} <= names.keys()+ for name in ("peer", "teacher", "research-assistant"):+ assert names[name]["source"] == "admin"+ assert names[name]["read_only"] is True+++def test_workspace_persona_shadows_admin_preset(personas_api) -> None:+ client, workspace, _admin = personas_api+ workspace.create("teacher", "Mine", "Local voice.")++ names = _by_name(client.get("/api/personas").json())+ assert names["teacher"]["source"] == "user"+ assert names["teacher"]["read_only"] is False+ assert names["teacher"]["description"] == "Mine"+ assert names["peer"]["source"] == "admin"+++def test_get_persona_falls_back_to_admin_preset(personas_api) -> None:+ client, workspace, _admin = personas_api+ assert workspace.list_personas() == []++ detail = client.get("/api/personas/peer").json()+ assert detail["name"] == "peer"+ assert detail["source"] == "admin"+ assert detail["read_only"] is True+ assert "content" in detail+++def test_create_writes_only_to_the_workspace(personas_api) -> None:+ client, workspace, admin = personas_api+ created = client.post(+ "/api/personas",+ json={"name": "coach", "description": "Local", "content": "Stay curious."},+ )+ assert created.status_code == 200, created.text+ assert created.json()["source"] == "user"+ assert {p.name for p in workspace.list_personas()} == {"coach"}+ assert "coach" not in {p.name for p in admin.list_personas()}diff --git a/tests/services/persona/test_persona_service.py b/tests/services/persona/test_persona_service.pyindex d71072857..19416c676 100644--- a/tests/services/persona/test_persona_service.py+++ b/tests/services/persona/test_persona_service.py@@ -11,6 +11,7 @@ from deeptutor.services.persona.service import (PersonaExistsError,PersonaNotFoundError,PersonaService,+ load_visible_for_context,)@@ -131,3 +132,31 @@ def test_seed_presets_is_idempotent_and_non_destructive(service: PersonaService)service.update("peer", content="---\nname: peer\ndescription: mine\n---\n\nCustom body.")assert service.seed_presets() == [] # nothing re-seededassert "Custom body." in service.get_detail("peer").content+++def test_load_visible_for_context_falls_back_to_admin_presets(+ tmp_path: Path,+) -> None:+ # Admin in an explicit workspace: local dir empty, presets live on the+ # account-level admin tree. Selecting one must still inject the body.+ workspace = PersonaService(root=tmp_path / "workspace" / "personas")+ admin = PersonaService(root=tmp_path / "admin" / "personas")+ admin.seed_presets()++ rendered = load_visible_for_context("teacher", workspace=workspace, admin=admin)+ assert "## Active Persona" in rendered+ assert "### Persona: teacher" in rendered+ assert workspace.load_for_context("teacher") == ""+++def test_load_visible_for_context_prefers_workspace_shadow(+ tmp_path: Path,+) -> None:+ workspace = PersonaService(root=tmp_path / "workspace" / "personas")+ admin = PersonaService(root=tmp_path / "admin" / "personas")+ admin.seed_presets()+ workspace.create("teacher", "Mine", "Local voice.")++ rendered = load_visible_for_context("teacher", workspace=workspace, admin=admin)+ assert "Local voice." in rendered+ assert "Teacher Mode" not in rendereddiff --git a/web/components/chat/home/StandaloneComposer.tsx b/web/components/chat/home/StandaloneComposer.tsxindex bdc515f4c..8e508ad68 100644--- a/web/components/chat/home/StandaloneComposer.tsx+++ b/web/components/chat/home/StandaloneComposer.tsx@@ -27,7 +27,9 @@ import { useTranslation } from "react-i18next";import ChatComposer from "@/components/chat/home/ChatComposer";import type { ContextBudget } from "@/components/chat/home/ContextBudgetChip";+import type { ResourceSelection } from "@/features/chat/ChatStateAdapter";import type { CapabilityDef } from "@/features/capabilities/presentation";+import type { ComposerResourceCatalog } from "@/hooks/useComposerResources";import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";import { useAttachmentLimits } from "@/lib/attachment-limits";@@ -187,6 +189,14 @@ interface StandaloneComposerProps {*/personaSelection?: string;onPersonaSelectionChange?: (persona: string) => void;+ /**+ * Skill / MCP narrowing for this conversation. Same contract as+ * `ChatComposer`: omit all three to keep inheriting the workspace+ * allowlist without a picker.+ */+ resourceCatalog?: ComposerResourceCatalog;+ resourceSelection?: ResourceSelection;+ onResourceSelectionChange?: (selection: ResourceSelection) => void;/** Hide the My Agents reference entry. */agentsAvailable?: boolean;/** Receives a function that drops text into the textarea (ask_user chips). */@@ -217,6 +227,9 @@ function StandaloneComposerImpl({onLLMSelectionChange,personaSelection,onPersonaSelectionChange,+ resourceCatalog,+ resourceSelection,+ onResourceSelectionChange,agentsAvailable = false,prefillInputRef,contextBudget = null,@@ -760,9 +773,16 @@ function StandaloneComposerImpl({if (!resourceReuse.policy.persona) setSelectedPersona(null);applyKnowledgeBases(retainedKnowledgeBases(selectedKnowledgeBases, agentNameSet, resourceReuse.policy));if (!resourceReuse.policy.memory) setSelectedMemoryFiles([]);+ if (onResourceSelectionChange) {+ const current = resourceSelection ?? { skills: [], mcp: [] };+ onResourceSelectionChange({+ skills: resourceReuse.policy.skills ? current.skills : [],+ mcp: resourceReuse.policy.mcp ? current.mcp : [],+ });+ }},[- resourceReuse, applyKnowledgeBases, agentNameSet,+ resourceReuse, applyKnowledgeBases, agentNameSet, onResourceSelectionChange, resourceSelection,attachments,awaitingUserReply,isStreaming,@@ -882,6 +902,9 @@ function StandaloneComposerImpl({onPersonaSelectionChange={onPersonaSelectionChange}personaSelectorOpen={personaSelectorOpen}onPersonaSelectorOpenChange={setPersonaSelectorOpen}+ resourceCatalog={resourceCatalog}+ resourceSelection={resourceSelection}+ onResourceSelectionChange={onResourceSelectionChange}llmOptions={llmOptions}activeLLMDefault={activeLLMDefault}llmSelection={llmSelection}diff --git a/web/components/space/learning/MasteryComposer.tsx b/web/components/space/learning/MasteryComposer.tsxindex 5c073d723..9de28c192 100644--- a/web/components/space/learning/MasteryComposer.tsx+++ b/web/components/space/learning/MasteryComposer.tsx@@ -6,10 +6,11 @@** A mastery session is a chat session, so the learner gets the whole* composer: attachments, `@`-space references, the knowledge picker, the- * model selector, dictation. Two of those controls are session-scoped- * rather than per-turn — the knowledge bases in play and the pinned model —- * so both are driven straight off the session state instead of a second- * copy inside the composer.+ * model selector, dictation, and the Skills/MCP narrowing Chat uses. Those+ * last controls are session-scoped rather than per-turn — knowledge bases,+ * the pinned model, and the resource selection — so they are driven+ * straight off the session state instead of a second copy inside the+ * composer.** What it does NOT get is the action menu. This screen runs one loop — the* tutor — and it used to open on "Chat" instead, which reached the same tutor@@ -26,6 +27,8 @@ import StandaloneComposer, {} from "@/components/chat/home/StandaloneComposer";import { MASTERY_CAPABILITY_VALUE } from "@/features/capabilities/presentation";import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";+import { useChatWorkspaces } from "@/hooks/useChatWorkspaces";+import { useComposerResources } from "@/hooks/useComposerResources";import { useContextBudget } from "@/hooks/useContextBudget";import { useWorkspaceChatActions } from "@/hooks/useWorkspaceChatActions";import {@@ -56,9 +59,12 @@ export function MasteryComposer({setKBs,setLLMSelection,setPersonaSelection,+ setResourceSelection,} = useChatStateAdapter();// Pins the turn to the tutor loop; returns no capabilities to offer.useWorkspaceChatActions({ pinnedCapability: MASTERY_CAPABILITY_VALUE });+ const { workspaces } = useChatWorkspaces();+ const resourceCatalog = useComposerResources(state.workspaceId, workspaces);const contextBudget = useContextBudget(state.messages);const { t } = useTranslation();@@ -127,6 +133,9 @@ export function MasteryComposer({onLLMSelectionChange={setLLMSelection}personaSelection={state.personaSelection}onPersonaSelectionChange={setPersonaSelection}+ resourceCatalog={resourceCatalog}+ resourceSelection={state.resourceSelection}+ onResourceSelectionChange={setResourceSelection}onSubmit={handleSubmit}onCancelStreaming={cancelStreamingTurn}// The suggested question *is* the placeholder once there is one: namingdiff --git a/web/tests/composer-reply-fallthrough.spec.tsx b/web/tests/composer-reply-fallthrough.spec.tsxindex 0e4d98909..bdf4c5b3e 100644--- a/web/tests/composer-reply-fallthrough.spec.tsx+++ b/web/tests/composer-reply-fallthrough.spec.tsx@@ -37,6 +37,8 @@ const chat = vi.hoisted(() => ({knowledgeBases: [],llmSelection: null,personaSelection: null,+ resourceSelection: { skills: [], mcp: [] },+ workspaceId: null,isStreaming: false,},}));@@ -50,6 +52,7 @@ vi.mock("@/features/chat/ChatStateAdapter", () => ({setKBs: () => undefined,setLLMSelection: () => undefined,setPersonaSelection: () => undefined,+ setResourceSelection: () => undefined,}),}));@@ -65,6 +68,14 @@ vi.mock("@/hooks/useContextBudget", () => ({useContextBudget: () => null,}));+vi.mock("@/hooks/useChatWorkspaces", () => ({+ useChatWorkspaces: () => ({ workspaces: [], error: "" }),+}));++vi.mock("@/hooks/useComposerResources", () => ({+ useComposerResources: () => ({ skills: [], mcp: [] }),+}));+/** Stands in for the real composer: one button that submits fixed text. */vi.mock("@/components/chat/home/StandaloneComposer", () => ({default: ({diff --git a/web/tests/mastery-composer-resources.spec.tsx b/web/tests/mastery-composer-resources.spec.tsxnew file mode 100644index 000000000..05fc2569d--- /dev/null+++ b/web/tests/mastery-composer-resources.spec.tsx@@ -0,0 +1,98 @@+import { render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { initI18n } from "@/i18n/init";+import type { ResourceSelection } from "@/features/chat/ChatStateAdapter";+import type { ComposerResourceCatalog } from "@/hooks/useComposerResources";++initI18n("en");++const captured = vi.hoisted(() => ({+ props: null as {+ resourceCatalog?: ComposerResourceCatalog;+ resourceSelection?: ResourceSelection;+ onResourceSelectionChange?: (selection: ResourceSelection) => void;+ } | null,+ setResourceSelection: vi.fn(),+ catalog: {+ skills: [{ id: "skill-1", name: "Tutor" }],+ mcp: [{ id: "mcp-1", name: "Search" }],+ },+ selection: { skills: ["skill-1"], mcp: [] as string[] },+}));++vi.mock("@/features/chat/ChatStateAdapter", () => ({+ useChatStateAdapter: () => ({+ state: {+ messages: [],+ knowledgeBases: [],+ llmSelection: null,+ personaSelection: "",+ resourceSelection: captured.selection,+ workspaceId: "ws-1",+ isStreaming: false,+ },+ sendMessage: vi.fn(),+ submitUserReply: vi.fn(),+ cancelStreamingTurn: () => undefined,+ setKBs: () => undefined,+ setLLMSelection: () => undefined,+ setPersonaSelection: () => undefined,+ setResourceSelection: captured.setResourceSelection,+ }),+}));++vi.mock("@/hooks/useWorkspaceChatActions", () => ({+ useWorkspaceChatActions: () => ({+ capabilities: [],+ activeCapabilityValue: "",+ selectCapability: () => undefined,+ }),+}));++vi.mock("@/hooks/useContextBudget", () => ({+ useContextBudget: () => null,+}));++vi.mock("@/hooks/useChatWorkspaces", () => ({+ useChatWorkspaces: () => ({ workspaces: [], error: "" }),+}));++vi.mock("@/hooks/useComposerResources", () => ({+ useComposerResources: () => captured.catalog,+}));++vi.mock("@/components/chat/home/StandaloneComposer", () => ({+ default: (props: {+ resourceCatalog?: ComposerResourceCatalog;+ resourceSelection?: ResourceSelection;+ onResourceSelectionChange?: (selection: ResourceSelection) => void;+ }) => {+ captured.props = props;+ return <div>composer</div>;+ },+}));++const { MasteryComposer } = await import(+ "@/components/space/learning/MasteryComposer"+);++describe("MasteryComposer resource wiring", () => {+ beforeEach(() => {+ captured.props = null;+ captured.setResourceSelection.mockClear();+ });++ it("passes catalog, selection, and the session setter through to the composer", () => {+ render(<MasteryComposer placeholder="Ask" />);+ expect(captured.props?.resourceCatalog).toEqual(captured.catalog);+ expect(captured.props?.resourceSelection).toEqual(captured.selection);+ expect(captured.props?.onResourceSelectionChange).toBe(+ captured.setResourceSelection,+ );++ const next = { skills: ["skill-1", "skill-2"], mcp: ["mcp-1"] };+ captured.props?.onResourceSelectionChange?.(next);+ expect(captured.setResourceSelection).toHaveBeenCalledWith(next);+ });+});diff --git a/web/tests/mastery-workspace-action.test.ts b/web/tests/mastery-workspace-action.test.tsindex 14cc85d9f..029e572b5 100644--- a/web/tests/mastery-workspace-action.test.ts+++ b/web/tests/mastery-workspace-action.test.ts@@ -80,3 +80,23 @@ test("the mastery composer pins its action and renders no action menu", () => {);assert.match(sessionHook, /capability: MASTERY_CAPABILITY_VALUE/);});++test("the mastery composer reuses Chat's skill and MCP pickers", () => {+ const source = fs.readFileSync(+ path.join(process.cwd(), "components/space/learning/MasteryComposer.tsx"),+ "utf8",+ );+ assert.match(source, /useComposerResources/);+ assert.match(source, /setResourceSelection/);+ assert.match(source, /resourceCatalog=\{resourceCatalog\}/);+ assert.match(source, /resourceSelection=\{state\.resourceSelection\}/);+ assert.match(source, /onResourceSelectionChange=\{setResourceSelection\}/);++ const standalone = fs.readFileSync(+ path.join(process.cwd(), "components/chat/home/StandaloneComposer.tsx"),+ "utf8",+ );+ assert.match(standalone, /resourceCatalog=\{resourceCatalog\}/);+ assert.match(standalone, /resourceSelection=\{resourceSelection\}/);+ assert.match(standalone, /onResourceSelectionChange=\{onResourceSelectionChange\}/);+});