Skip to content

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

fix

Bingxi Zhao (Frank)9ce7ba9059e3
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index d167f447c..f48dde2e9 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -527,6 +527,7 @@ async def health_live():
return {"status": "alive"}
[email protected]("/health", include_in_schema=False)
@app.get("/health/ready")
async def health_ready(request: Request):
if not bool(getattr(request.app.state, "ready", False)):
diff --git a/deeptutor/api/router_index.json b/deeptutor/api/router_index.json
index 06955b938..18d4d2a4c 100644
--- a/deeptutor/api/router_index.json
+++ b/deeptutor/api/router_index.json
@@ -1,5 +1,5 @@
{
- "fingerprint": "83363f052eafc8a39b8d91e575ee819a8aa01b7b86d06a19167c718f5abcf757",
+ "fingerprint": "6d90ec2c45a1d9f3f152c7577772bcdd05ea8b8f2b22a7dcca57e0d09db0097b",
"routers": {
"deeptutor.api.routers.auth:router": [
{
@@ -3835,6 +3835,30 @@
"PUT"
]
},
+ {
+ "path": "/page-customization",
+ "name": "get_page_customization",
+ "kind": "http",
+ "methods": [
+ "GET"
+ ]
+ },
+ {
+ "path": "/page-customization/chat",
+ "name": "update_chat_page_customization",
+ "kind": "http",
+ "methods": [
+ "PUT"
+ ]
+ },
+ {
+ "path": "/page-customization/learning",
+ "name": "update_learning_page_customization",
+ "kind": "http",
+ "methods": [
+ "PUT"
+ ]
+ },
{
"path": "/ui",
"name": "update_ui_settings",
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 8b7579bc5..1595630f3 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -624,12 +624,22 @@ _LEARNER_KB_READ_ROUTES = frozenset(
)
+_PERSONAL_PAGE_ROUTES = frozenset(
+ {
+ ("GET", "/api/settings/page-customization"),
+ ("PUT", "/api/settings/page-customization/chat"),
+ ("PUT", "/api/settings/page-customization/learning"),
+ }
+)
+
+
_LEARNER_SETTINGS_WRITE_ROUTES = frozenset(
{
# UI preferences resolve through the per-user path service into the
# caller's OWN workspace (interface.json) — saving theme/language is
# safe for learning accounts.
("PUT", "/api/settings/ui"),
+ *_PERSONAL_PAGE_ROUTES,
# Per-user settings draft document. Applying a draft to the runtime
# catalog stays admin-gated in the endpoint itself.
("PUT", "/api/settings/draft"),
@@ -720,6 +730,10 @@ async def require_learning_surface(
)
route_path = _resolved_route_path(request)
+ # Personal presentation does not grant a learning surface. Any authenticated
+ # learner may customize these two pages, including reading-only accounts.
+ if (request.method, route_path) in _PERSONAL_PAGE_ROUTES:
+ return
# The landing page combines independent learning surfaces (#1987). Admit
# any granted surface; the handler filters its readers with the same policy.
if (
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 983dff8ec..a0d8afbd9 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -78,6 +78,11 @@ from deeptutor.services.settings.interface_settings import (
from deeptutor.services.settings.interface_settings import (
get_enabled_optional_tools as _get_enabled_optional_tools,
)
+from deeptutor.services.settings.page_customization import (
+ ChatPageCustomization,
+ LearningPageCustomization,
+ PageCustomization,
+)
from deeptutor.services.settings.starter_settings import (
TRACE_COUNT_RANGE as STARTER_TRACE_COUNT_RANGE,
)
@@ -2150,6 +2155,36 @@ async def get_ui_settings():
return {field: settings.get(field) for field in PRESESSION_UI_FIELDS}
+# Private: user-authored starting prompts must never enter the public /ui payload.
+def _page_customization() -> PageCustomization:
+ return PageCustomization.model_validate(load_ui_settings().get("page_customization") or {})
+
+
[email protected]("/page-customization")
+async def get_page_customization():
+ return _page_customization().model_dump()
+
+
+def _save_page_section(section: str, value: BaseModel) -> dict[str, Any]:
+ def update(stored):
+ current = PageCustomization.model_validate(stored.get("page_customization") or {})
+ setattr(current, section, value)
+ return {**stored, "page_customization": current.model_dump()}
+
+ atomic_update(_settings_file(), update)
+ return _page_customization().model_dump()
+
+
[email protected]("/page-customization/chat")
+async def update_chat_page_customization(update: ChatPageCustomization):
+ return _save_page_section("chat", update)
+
+
[email protected]("/page-customization/learning")
+async def update_learning_page_customization(update: LearningPageCustomization):
+ return _save_page_section("learning", update)
+
+
@router.put("/ui")
async def update_ui_settings(update: UISettingsUpdate):
"""Merge frontend partial update into current UI settings.
diff --git a/deeptutor/services/partners/module_service.py b/deeptutor/services/partners/module_service.py
index a32622a3f..823e6ae99 100644
--- a/deeptutor/services/partners/module_service.py
+++ b/deeptutor/services/partners/module_service.py
@@ -6,7 +6,7 @@ async def start_partners(application_container) -> None:
manager = get_partner_manager()
manager.configure_runtime_owner(application_container.worker_id)
- await manager.autostart_partners(application_container)
+ await manager.auto_start_partners()
async def stop_partners(application_container) -> None:
diff --git a/deeptutor/services/settings/page_customization.py b/deeptutor/services/settings/page_customization.py
new file mode 100644
index 000000000..ccdb09481
--- /dev/null
+++ b/deeptutor/services/settings/page_customization.py
@@ -0,0 +1,46 @@
+"""Personal page presentation; never grants capabilities or changes installed modules."""
+
+from typing import Annotated, Literal
+
+from pydantic import BaseModel, ConfigDict, Field, StringConstraints
+
+ShortText = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=160)]
+PromptText = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=4000)]
+Guide = Literal["explain", "solve", "practice", "plan", "research"]
+
+
+class StarterPrompt(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ label: ShortText
+ prompt: PromptText
+
+
+class ComposerControls(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ skills: bool = True
+ mcp: bool = True
+ partners: bool = True
+ preferences: bool = True
+ voice: bool = True
+
+
+class ChatPageCustomization(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ hidden_modes: list[ShortText] = Field(default_factory=list, max_length=64)
+ controls: ComposerControls = Field(default_factory=ComposerControls)
+ # Missing group follows translated defaults; [] deliberately removes all its prompts.
+ starters: dict[Guide, Annotated[list[StarterPrompt], Field(max_length=20)]] = Field(
+ default_factory=dict
+ )
+
+
+class LearningPageCustomization(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ hidden_features: list[Literal["books", "mastery", "practice", "reading"]] = Field(
+ default_factory=list, max_length=4
+ )
+
+
+class PageCustomization(BaseModel):
+ chat: ChatPageCustomization = Field(default_factory=ChatPageCustomization)
+ learning: LearningPageCustomization = Field(default_factory=LearningPageCustomization)
diff --git a/tests/api/test_page_customization.py b/tests/api/test_page_customization.py
new file mode 100644
index 000000000..2790ad20b
--- /dev/null
+++ b/tests/api/test_page_customization.py
@@ -0,0 +1,124 @@
+import json
+
+from pydantic import ValidationError
+import pytest
+
+from deeptutor.api.routers import settings
+from deeptutor.services.settings.page_customization import (
+ ChatPageCustomization,
+ LearningPageCustomization,
+)
+
+
+async def test_customization_sections_preserve_other_settings_and_are_private(
+ monkeypatch, tmp_path
+):
+ path = tmp_path / "interface.json"
+ path.write_text(json.dumps({"theme": "dark", "language": "zh"}))
+ monkeypatch.setattr(settings, "_settings_file", lambda: path)
+ await settings.update_learning_page_customization(
+ LearningPageCustomization(hidden_features=["mastery"])
+ )
+ response = await settings.update_chat_page_customization(
+ ChatPageCustomization(
+ hidden_modes=["deep_research"],
+ controls={"voice": False},
+ starters={
+ "explain": [{"label": "My title", "prompt": "Private personal prompt"}],
+ "solve": [],
+ },
+ )
+ )
+ assert response["learning"]["hidden_features"] == ["mastery"]
+ assert response["chat"]["controls"]["voice"] is False
+ assert response["chat"]["controls"]["skills"] is True
+ assert response["chat"]["starters"]["solve"] == []
+ assert json.loads(path.read_text())["theme"] == "dark"
+ assert "page_customization" not in await settings.get_ui_settings()
+ # Changing the account-resolved file cannot expose the previous account's prompts.
+ monkeypatch.setattr(settings, "_settings_file", lambda: tmp_path / "another-user.json")
+ assert (await settings.get_page_customization())["chat"]["starters"] == {}
+
+
+ "payload",
+ [
+ {"starters": {"unknown": []}},
+ {"starters": {"explain": [{"label": " ", "prompt": "ok"}]}},
+ {"starters": {"explain": [{"label": "ok", "prompt": "x" * 4001}]}},
+ {"starters": {"explain": [{"label": "ok", "prompt": "ok"}] * 21}},
+ {"controls": {"install_module": True}},
+ ],
+)
+def test_customization_rejects_invalid_or_unbounded_input(payload):
+ with pytest.raises(ValidationError):
+ ChatPageCustomization.model_validate(payload)
+
+
+def test_learner_can_edit_personal_pages_but_not_runtime():
+ from deeptutor.api.routers.auth import _learning_surface_for_path
+
+ for method, path in [
+ ("GET", "/api/settings/page-customization"),
+ ("PUT", "/api/settings/page-customization/chat"),
+ ("PUT", "/api/settings/page-customization/learning"),
+ ]:
+ assert _learning_surface_for_path(path, method=method, route_path=path) == "chat"
+ assert (
+ _learning_surface_for_path(
+ "/api/settings/catalog", method="PUT", route_path="/api/settings/catalog"
+ )
+ == ""
+ )
+
+
+async def test_legacy_health_url_uses_readiness_handler():
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock
+
+ from deeptutor.api.main import app, health_ready
+
+ routes = {
+ route.path: route
+ for route in app.routes
+ if getattr(route, "path", "") in {"/health", "/health/ready"}
+ }
+ assert routes["/health"].endpoint is routes["/health/ready"].endpoint
+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(ready=False)))
+ assert (await health_ready(request)).status_code == 503
+ request.app.state.ready = True
+ request.app.state.application_container = SimpleNamespace(
+ coordinator=SimpleNamespace(health=AsyncMock(return_value=True))
+ )
+ assert await health_ready(request) == {"status": "ready"}
+
+
+async def test_reading_only_learner_can_customize_pages_without_chat_access(monkeypatch):
+ from types import SimpleNamespace
+
+ from starlette.requests import Request
+
+ from deeptutor.api.routers.auth import require_learning_surface
+ from deeptutor.multi_user import learning_access
+
+ def deny_surface(*args, **kwargs):
+ raise AssertionError("Personal page choices must not require a chat grant")
+
+ monkeypatch.setattr(learning_access, "assert_learning_surface", deny_surface)
+ for method, path in [
+ ("GET", "/api/settings/page-customization"),
+ ("PUT", "/api/settings/page-customization/learning"),
+ ]:
+ request = Request(
+ {
+ "type": "http",
+ "method": method,
+ "path": path,
+ "headers": [],
+ "route": SimpleNamespace(path=path),
+ }
+ )
+ await require_learning_surface(request, None)
diff --git a/tests/services/partners/test_module_service.py b/tests/services/partners/test_module_service.py
new file mode 100644
index 000000000..c6fcba317
--- /dev/null
+++ b/tests/services/partners/test_module_service.py
@@ -0,0 +1,32 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from deeptutor.services.partners import manager as manager_module
+from deeptutor.services.partners.manager import PartnerManager
+from deeptutor.services.partners.module_service import start_partners, stop_partners
+
+
+async def test_module_starts_real_manager_and_preserves_autostart_on_shutdown(monkeypatch):
+ # Exercise the real public method (an unrestricted mock hid the name mismatch).
+ manager = PartnerManager()
+ monkeypatch.setattr(manager_module, "_manager", manager)
+ import deeptutor.services.partners as partners
+
+ monkeypatch.setattr(partners, "get_partner_manager", lambda: manager)
+ monkeypatch.setattr(manager, "_discover_partner_ids", lambda: ["enabled", "disabled"])
+ monkeypatch.setattr(manager, "_load_auto_start", lambda pid, **kw: pid == "enabled")
+ config = object()
+ monkeypatch.setattr(manager, "load_config", lambda pid: config)
+ start = AsyncMock()
+ monkeypatch.setattr(manager, "start_partner", start)
+ stop = AsyncMock()
+ monkeypatch.setattr(manager, "stop_all", stop)
+ owner = SimpleNamespace(worker_id="test-worker")
+ await start_partners(owner)
+ assert manager.runtime_owner_id == "test-worker"
+ start.assert_awaited_once_with("enabled", config)
+ await stop_partners(owner)
+ stop.assert_awaited_once_with(preserve_auto_start=True)
diff --git a/web/app/(workspace)/layout.tsx b/web/app/(workspace)/layout.tsx
index 1c257916f..527f22f80 100644
--- a/web/app/(workspace)/layout.tsx
+++ b/web/app/(workspace)/layout.tsx
@@ -1,3 +1,4 @@
+import { PageCustomizationProvider } from "@/context/PageCustomizationContext";
import CalendarRuntime from "@/features/calendar/components/CalendarRuntime";
import TaskBoardRuntime from "@/components/tasks/TaskBoardRuntime";
import WorkspaceSidebar from "@/components/sidebar/WorkspaceSidebar";
@@ -17,6 +18,7 @@ export default function WorkspaceLayout({
}>) {
return (
<CapabilityAccessProvider>
+ <PageCustomizationProvider>
<Suspense>
<WorkspaceRuntimeBoundary>
<CalendarRuntime>
@@ -36,6 +38,7 @@ export default function WorkspaceLayout({
</CalendarRuntime>
</WorkspaceRuntimeBoundary>
</Suspense>
+ </PageCustomizationProvider>
</CapabilityAccessProvider>
);
}
diff --git a/web/app/(workspace)/learning/new/page.tsx b/web/app/(workspace)/learning/new/page.tsx
new file mode 100644
index 000000000..85d720037
--- /dev/null
+++ b/web/app/(workspace)/learning/new/page.tsx
@@ -0,0 +1,5 @@
+import NewLearningPage from '@/components/learning/NewLearningPage'
+
+export default function Page() {
+ return <NewLearningPage />
+}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index 29b90bbba..676080e89 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -95,6 +95,7 @@ import { isQuoteAttachment, quoteText } from "@/lib/quote-attachments";
import type { AttachmentProcessingItem } from "@/features/chat/selectors/attachment-processing";
import Tooltip from "@/shared/ui/Tooltip";
import { useCapabilityLabel } from "@/features/ui-layout/tokens";
+import { usePageCustomization } from "@/context/PageCustomizationContext";
import { useUiLayout } from "@/hooks/useUiLayout";
interface PendingAttachment {
@@ -247,7 +248,8 @@ export default memo(function ChatComposer({
capabilityNeedsConfig,
capabilityConfigConfirmed,
onRequestConfigConfirm,
- capabilities,
+ capabilities: allCapabilities,
+ customizable = false,
onSetCapMenuOpen,
onSetSpaceMenuOpen,
onToggleKB,
@@ -384,6 +386,7 @@ export default memo(function ChatComposer({
*/
onRequestConfigConfirm: () => void;
capabilities: CapabilityDef[];
+ customizable?: boolean;
onSetCapMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
onSetSpaceMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
onToggleKB: (name: string) => void;
@@ -483,6 +486,9 @@ export default memo(function ChatComposer({
}) {
const { t } = useTranslation();
const capabilityLabel = useCapabilityLabel();
+ const { value: pageCustomization } = usePageCustomization();
+ const controls = customizable ? pageCustomization.chat.controls : undefined;
+ const capabilities = customizable ? allCapabilities.filter(cap => !pageCustomization.chat.hidden_modes.includes(cap.value)) : allCapabilities;
// The modern layout picks the mode in the tray and writes it at the start
// of the message; the classic one keeps its chip in the toolbar.
const modeInTray = useUiLayout() === "modern" && showCapabilityChip;
@@ -1349,7 +1355,7 @@ export default memo(function ChatComposer({
{contextBudget ? <ContextBudgetChip budget={contextBudget} /> : null}
- <Tooltip
+ {(controls?.voice !== false || recorder.state !== "idle") && <Tooltip
label={recorder.state === "recording" ? t("Stop recording") : t("Record voice")}
description={recorder.error || undefined}
side="top"
@@ -1378,7 +1384,7 @@ export default memo(function ChatComposer({
<Mic size={16} strokeWidth={1.9} />
)}
</button>
- </Tooltip>
+ </Tooltip>}
{/* The thing you press is the thing that's working is the
thing you press to stop — one element for the whole turn,
@@ -1439,6 +1445,7 @@ export default memo(function ChatComposer({
</div>
{trayMode || (resourceCatalog && resourceSelection && onResourceSelectionChange) || answerMode || partnerLinks || trayEnd ? (
<ComposerTray
+ controls={controls}
placement={hasMessages || docked ? "up" : "down"}
mode={trayMode}
resources={
diff --git a/web/components/chat/home/ComposerTray.tsx b/web/components/chat/home/ComposerTray.tsx
index da3183454..75dae185e 100644
--- a/web/components/chat/home/ComposerTray.tsx
+++ b/web/components/chat/home/ComposerTray.tsx
@@ -24,6 +24,7 @@ import {
} from "./ComposerTrayMenu";
import AnswerModeMenu, { PartnerLinkMenu, type AnswerModeProps, type PartnerLinkProps } from "./AnswerModeMenu";
import { ConnectorHubIcon, SkillDeckIcon, modeIcon } from "./ComposerIcons";
+import type { ComposerControls } from "@/lib/page-customization";
import { useTrayFold } from "./ComposerTrayFold";
const STATUS_DOT: Record<McpServerStatus, string> = {
@@ -120,6 +121,7 @@ export interface TrayMode {
* drag or a click, until only that edge shows.
*/
export function ComposerTray({
+ controls,
placement,
mode,
resources,
@@ -129,6 +131,7 @@ export function ComposerTray({
}: {
/** Lists open toward the page's free space: below on the home screen, above in a conversation. */
placement: TrayPlacement;
+ controls?: ComposerControls;
mode?: TrayMode;
resources?: TrayResources;
partners?: PartnerLinkProps;
@@ -166,10 +169,10 @@ export function ComposerTray({
</Tooltip>
<div id={rowId} className="dt-tray-bar" inert={fold.away}>
{mode && <ModeMenu {...mode} placement={placement} />}
- {resources && <SkillsMenu {...resources} placement={placement} />}
- {resources && <ConnectorsMenu {...resources} placement={placement} />}
- {partners && <PartnerLinkMenu {...partners} placement={placement} />}
- {answer && <AnswerModeMenu {...answer} placement={placement} />}
+ {resources && controls?.skills !== false && <SkillsMenu {...resources} placement={placement} />}
+ {resources && controls?.mcp !== false && <ConnectorsMenu {...resources} placement={placement} />}
+ {partners && controls?.partners !== false && <PartnerLinkMenu {...partners} placement={placement} />}
+ {answer && controls?.preferences !== false && <AnswerModeMenu {...answer} placement={placement} />}
{end}
</div>
</m.div>
diff --git a/web/components/chat/home/StarterSuggestions.tsx b/web/components/chat/home/StarterSuggestions.tsx
index 2e5628602..3e5db7652 100644
--- a/web/components/chat/home/StarterSuggestions.tsx
+++ b/web/components/chat/home/StarterSuggestions.tsx
@@ -16,6 +16,8 @@ import {
import { useOutsideClick } from "@/hooks/use-outside-click";
import { CornerDownLeft, Loader2, RefreshCw } from "lucide-react";
import { activeWorkspaceId, scopedUrl } from "@/lib/workspace-scope";
+import { usePageCustomization } from "@/context/PageCustomizationContext";
+import { starterPrompts, type StarterGroup } from "@/lib/page-customization";
import { apiFetch, apiUrl } from "@/lib/api";
interface Suggestion {
@@ -63,14 +65,13 @@ const ready = (items: Suggestion[]): View => ({ kind: "ready", item: items[0] })
* ask for when a detail is missing, so a learner can send one as it is and the
* tutor fills the gap with a question rather than a guess.
*/
-const GUIDES: readonly { id: string; icon: StarterIcon }[] = [
+const GUIDES: readonly { id: StarterGroup; icon: StarterIcon }[] = [
{ id: "explain", icon: ExplainMark },
{ id: "solve", icon: SolveMark },
{ id: "practice", icon: PracticeMark },
{ id: "plan", icon: PlanMark },
{ id: "research", icon: ResearchMark },
];
-const PER_GUIDE = [1, 2, 3, 4];
/**
* What to start with, under the home composer.
@@ -100,6 +101,7 @@ export default function StarterSuggestions({
workspaceId?: string;
}) {
const { t } = useTranslation();
+ const { value: { chat } } = usePageCustomization();
const [view, setView] = useState<View>({ kind: "loading" });
const [open, setOpen] = useState<string | null>(null);
const panelId = useId();
@@ -267,7 +269,8 @@ export default function StarterSuggestions({
</>
);
}
- const guide = GUIDES.find((entry) => entry.id === open);
+ const guides = GUIDES.filter(entry => starterPrompts(chat, entry.id, t).length > 0);
+ const guide = guides.find((entry) => entry.id === open);
return (
// max-w-[768px] + px-6 mirrors ChatComposer's own empty-state container.
@@ -284,7 +287,7 @@ export default function StarterSuggestions({
one never moves the composer the page is centred on. */}
<div ref={menuRef} className="dt-starter-menu">
<div className="dt-starter-tabs">
- {GUIDES.map((entry) => (
+ {guides.map((entry) => (
<button
key={entry.id}
type="button"
@@ -311,8 +314,7 @@ export default function StarterSuggestions({
{/* Keyed so switching ways swaps the rows in place: the card stays,
only its content changes. */}
<div key={guide.id} className="dt-starter-card-body">
- {PER_GUIDE.map((n) => {
- const prompt = t(`starters.${guide.id}.${n}.prompt`);
+ {starterPrompts(chat, guide.id, t).map(({ label, prompt }, n) => {
return (
// The whole request shows on hover: what the box will hold.
<Tooltip key={n} label={prompt} side="top" as="div" className="dt-starter-item" delay={500}>
@@ -325,7 +327,7 @@ export default function StarterSuggestions({
}}
className="dt-starter-row"
>
- <span className="min-w-0 flex-1 truncate">{t(`starters.${guide.id}.${n}`)}</span>
+ <span className="min-w-0 flex-1 truncate">{label}</span>
<CornerDownLeft size={14} strokeWidth={1.8} aria-hidden className="dt-starter-enter" />
</button>
</Tooltip>
diff --git a/web/components/customization/PageCustomizeButton.tsx b/web/components/customization/PageCustomizeButton.tsx
new file mode 100644
index 000000000..48d1671e1
--- /dev/null
+++ b/web/components/customization/PageCustomizeButton.tsx
@@ -0,0 +1,56 @@
+'use client'
+
+import { useState } from 'react'
+import { createPortal } from 'react-dom'
+import dynamic from 'next/dynamic'
+import { SlidersHorizontal } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import Tooltip from '@/shared/ui/Tooltip'
+import type { CapabilityDef } from '@/features/capabilities/presentation'
+import { usePageCustomization } from '@/context/PageCustomizationContext'
+
+const PageCustomizeDialog = dynamic(() => import('./PageCustomizeDialog'))
+
+export function PageCustomizeButton({
+ page,
+ capabilities = [],
+ learningKinds,
+ compact = false,
+}: {
+ page: 'chat' | 'learning'
+ capabilities?: CapabilityDef[]
+ learningKinds?: string[]
+ compact?: boolean
+}) {
+ const { t } = useTranslation()
+ const [open, setOpen] = useState(false)
+ const { value, loading, error, reload } = usePageCustomization()
+ return (
+ <>
+ <Tooltip label={t(error ? 'customize.loadError' : 'customize.title')}>
+ <button
+ type="button"
+ aria-label={t(error ? 'customize.loadError' : 'customize.title')}
+ aria-haspopup="dialog"
+ disabled={loading}
+ onClick={() => (error ? reload() : setOpen(true))}
+ className={`inline-flex h-8 items-center justify-center gap-2 rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring ${compact ? 'w-8' : 'px-3 text-xs'}`}
+ >
+ <SlidersHorizontal size={15} strokeWidth={1.7} />
+ {!compact && <span>{t('customize.title')}</span>}
+ </button>
+ </Tooltip>
+ {open &&
+ createPortal(
+ <PageCustomizeDialog
+ page={page}
+ initial={value}
+ capabilities={capabilities}
+ learningKinds={learningKinds}
+ onClose={() => setOpen(false)}
+ />,
+ document.body
+ )}
+ </>
+ )
+}
diff --git a/web/components/customization/PageCustomizeDialog.tsx b/web/components/customization/PageCustomizeDialog.tsx
new file mode 100644
index 000000000..33aabd220
--- /dev/null
+++ b/web/components/customization/PageCustomizeDialog.tsx
@@ -0,0 +1,392 @@
+'use client'
+
+import { useState } from 'react'
+import { Loader2, Plus, RotateCcw, Trash2 } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { Dialog } from '@/shared/ui/Dialog'
+import { usePageCustomization } from '@/context/PageCustomizationContext'
+import {
+ DEFAULT_PAGE_CUSTOMIZATION,
+ STARTER_GROUPS,
+ starterPrompts,
+ toggleHidden,
+ type PageCustomization,
+ type StarterGroup,
+ type ComposerControls,
+} from '@/lib/page-customization'
+import type { CapabilityDef } from '@/features/capabilities/presentation'
+import { useCapabilityLabel } from '@/features/ui-layout/tokens'
+import { LEARNING_SURFACES } from '@/components/learning/surfaces'
+
+const inputClass =
+ 'w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none transition-shadow focus:border-ring focus:ring-2 focus:ring-ring/15'
+const actionClass =
+ 'inline-flex items-center justify-center gap-2 rounded-lg px-3 py-2 text-xs font-medium transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-50'
+
+export function ChoiceRow({
+ label,
+ description,
+ checked,
+ onChange,
+}: {
+ label: string
+ description?: string
+ checked: boolean
+ onChange: () => void
+}) {
+ return (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={checked}
+ onClick={onChange}
+ className="flex w-full cursor-pointer items-center gap-4 rounded-xl border border-border p-3.5 text-left transition-colors hover:bg-muted/40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"
+ >
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium">{label}</span>
+ {description && (
+ <span className="mt-1 block text-xs leading-relaxed text-muted-foreground">
+ {description}
+ </span>
+ )}
+ </span>
+ <span
+ aria-hidden
+ className={`flex h-5 w-9 shrink-0 items-center rounded-full p-0.5 transition-colors ${checked ? 'bg-primary' : 'bg-muted-foreground/25'}`}
+ >
+ <span
+ className={`h-4 w-4 rounded-full bg-background shadow-sm transition-transform motion-reduce:transition-none ${checked ? 'translate-x-4' : ''}`}
+ />
+ </span>
+ </button>
+ )
+}
+
+export default function PageCustomizeDialog({
+ page,
+ initial,
+ capabilities,
+ learningKinds,
+ onClose,
+}: {
+ page: 'chat' | 'learning'
+ initial: PageCustomization
+ capabilities: CapabilityDef[]
+ learningKinds?: string[]
+ onClose: () => void
+}) {
+ const { t } = useTranslation()
+ const capabilityLabel = useCapabilityLabel()
+ const { save, loading, error: loadError, reload } = usePageCustomization()
+ const [draft, setDraft] = useState(() => structuredClone(initial))
+ const [tab, setTab] = useState<'modes' | 'controls' | 'starters'>('modes')
+ const [group, setGroup] = useState<StarterGroup>('explain')
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState(false)
+ const prompts = starterPrompts(draft.chat, group, t)
+ const invalid = Object.values(draft.chat.starters).some(rows =>
+ rows?.some(row => !row.label.trim() || !row.prompt.trim())
+ )
+ const updatePrompts = (rows: typeof prompts) =>
+ setDraft(previous => ({
+ ...previous,
+ chat: { ...previous.chat, starters: { ...previous.chat.starters, [group]: rows } },
+ }))
+ async function commit() {
+ setSaving(true)
+ setError(false)
+ try {
+ await save(page, draft[page])
+ onClose()
+ } catch {
+ setError(true)
+ setSaving(false)
+ }
+ }
+ return (
+ <Dialog
+ open
+ title={t('customize.title')}
+ description={t('customize.description')}
+ onClose={onClose}
+ closeLabel={t('Close')}
+ size="lg"
+ busy={saving}
+ footer={
+ <div className="flex w-full flex-wrap items-center justify-between gap-3">
+ <button
+ type="button"
+ disabled={saving}
+ className={`${actionClass} text-muted-foreground hover:bg-muted`}
+ onClick={() =>
+ setDraft(previous => ({
+ ...previous,
+ [page]: structuredClone(DEFAULT_PAGE_CUSTOMIZATION[page]),
+ }))
+ }
+ >
+ <RotateCcw size={14} />
+ {t('customize.reset')}
+ </button>
+ <div className="flex gap-2">
+ <button
+ type="button"
+ disabled={saving}
+ className={`${actionClass} hover:bg-muted`}
+ onClick={onClose}
+ >
+ {t('Cancel')}
+ </button>
+ <button
+ type="button"
+ disabled={saving || loading || loadError || invalid}
+ onClick={() => void commit()}
+ className={`${actionClass} bg-primary text-primary-foreground hover:opacity-90`}
+ >
+ {saving && <Loader2 size={14} className="animate-spin" />}
+ {t(saving ? 'Saving...' : 'Save')}
+ </button>
+ </div>
+ </div>
+ }
+ >
+ {(error || loadError) && (
+ <div
+ role="alert"
+ className="mb-4 rounded-lg bg-destructive/10 p-3 text-sm text-destructive"
+ >
+ {t('customize.saveError')}
+ {loadError && (
+ <button type="button" className="ml-2 underline" onClick={reload}>
+ {t('Retry')}
+ </button>
+ )}
+ </div>
+ )}
+ {loading ? (
+ <div role="status" className="flex justify-center p-12">
+ <Loader2 className="animate-spin text-muted-foreground" />
+ </div>
+ ) : (
+ <>
+ {page === 'chat' ? (
+ <>
+ <div
+ className="mb-5 flex gap-1 rounded-xl bg-muted/60 p-1"
+ role="group"
+ aria-label={t('customize.sections')}
+ >
+ {(['modes', 'controls', 'starters'] as const).map(item => (
+ <button
+ key={item}
+ type="button"
+ aria-pressed={tab === item}
+ onClick={() => setTab(item)}
+ className={`flex-1 rounded-lg px-3 py-2 text-sm transition-colors ${tab === item ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
+ >
+ {t(`customize.${item}`)}
+ </button>
+ ))}
+ </div>
+ {tab === 'modes' && (
+ <div className="space-y-2">
+ <p className="mb-3 text-xs leading-relaxed text-muted-foreground">
+ {t('customize.modesHint')}
+ </p>
+ {capabilities
+ .filter(cap => cap.value && !cap.legacy)
+ .map(cap => (
+ <ChoiceRow
+ key={cap.value}
+ label={capabilityLabel(cap)}
+ description={t(cap.description)}
+ checked={!draft.chat.hidden_modes.includes(cap.value)}
+ onChange={() =>
+ setDraft(previous => ({
+ ...previous,
+ chat: {
+ ...previous.chat,
+ hidden_modes: toggleHidden(previous.chat.hidden_modes, cap.value),
+ },
+ }))
+ }
+ />
+ ))}
+ </div>
+ )}
+ {tab === 'controls' && (
+ <div className="space-y-2">
+ {(
+ [
+ 'skills',
+ 'mcp',
+ 'partners',
+ 'preferences',
+ 'voice',
+ ] as (keyof ComposerControls)[]
+ ).map(key => (
+ <ChoiceRow
+ key={key}
+ label={t(`customize.control.${key}`)}
+ checked={draft.chat.controls[key]}
+ onChange={() =>
+ setDraft(previous => ({
+ ...previous,
+ chat: {
+ ...previous.chat,
+ controls: {
+ ...previous.chat.controls,
+ [key]: !previous.chat.controls[key],
+ },
+ },
+ }))
+ }
+ />
+ ))}
+ </div>
+ )}
+ {tab === 'starters' && (
+ <>
+ <div
+ className="mb-4 flex flex-wrap gap-2"
+ role="group"
+ aria-label={t('customize.starters')}
+ >
+ {STARTER_GROUPS.map(key => (
+ <button
+ type="button"
+ key={key}
+ aria-pressed={group === key}
+ onClick={() => setGroup(key)}
+ className={`rounded-full px-3 py-1.5 text-xs transition-colors ${group === key ? 'bg-primary text-primary-foreground' : 'bg-muted/60 text-muted-foreground hover:bg-muted'}`}
+ >
+ {t(`starters.${key}`)}
+ </button>
+ ))}
+ </div>
+ <div className="space-y-3">
+ {prompts.map((row, index) => (
+ <div
+ key={`${group}-${index}`}
+ className="rounded-xl border border-border bg-muted/15 p-3"
+ >
+ <div className="mb-2 flex items-start gap-2">
+ <label className="min-w-0 flex-1">
+ <span className="mb-1.5 block text-xs text-muted-foreground">
+ {t('customize.promptLabel')}
+ </span>
+ <input
+ aria-label={`${t('customize.promptLabel')} ${index + 1}`}
+ value={row.label}
+ maxLength={160}
+ className={inputClass}
+ onChange={event =>
+ updatePrompts(
+ prompts.map((item, i) =>
+ i === index ? { ...item, label: event.target.value } : item
+ )
+ )
+ }
+ />
+ </label>
+ <button
+ type="button"
+ aria-label={`${t('customize.removePrompt')} ${index + 1}`}
+ onClick={() => updatePrompts(prompts.filter((_, i) => i !== index))}
+ className="mt-6 rounded-lg p-2 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
+ >
+ <Trash2 size={16} />
+ </button>
+ </div>
+ <label>
+ <span className="mb-1.5 block text-xs text-muted-foreground">
+ {t('customize.promptText')}
+ </span>
+ <textarea
+ aria-label={`${t('customize.promptText')} ${index + 1}`}
+ value={row.prompt}
+ maxLength={4000}
+ rows={3}
+ className={`${inputClass} resize-y`}
+ onChange={event =>
+ updatePrompts(
+ prompts.map((item, i) =>
+ i === index ? { ...item, prompt: event.target.value } : item
+ )
+ )
+ }
+ />
+ </label>
+ </div>
+ ))}
+ {!prompts.length && (
+ <p className="rounded-xl border border-dashed border-border p-6 text-center text-sm text-muted-foreground">
+ {t('customize.emptyPrompts')}
+ </p>
+ )}
+ </div>
+ <div className="mt-3 flex flex-wrap items-center justify-between gap-2">
+ <button
+ type="button"
+ disabled={prompts.length >= 20}
+ onClick={() => updatePrompts([...prompts, { label: '', prompt: '' }])}
+ className={`${actionClass} border border-border hover:bg-muted`}
+ >
+ <Plus size={14} />
+ {t('customize.addPrompt')}
+ </button>
+ <button
+ type="button"
+ className={`${actionClass} text-muted-foreground hover:bg-muted`}
+ onClick={() =>
+ setDraft(previous => {
+ const starters = { ...previous.chat.starters }
+ delete starters[group]
+ return { ...previous, chat: { ...previous.chat, starters } }
+ })
+ }
+ >
+ {t('customize.resetGroup')}
+ </button>
+ </div>
+ {invalid && (
+ <p role="status" className="mt-2 text-xs text-muted-foreground">
+ {t('customize.requiredPrompts')}
+ </p>
+ )}
+ </>
+ )}
+ </>
+ ) : (
+ <div className="space-y-2">
+ <p className="mb-3 text-xs leading-relaxed text-muted-foreground">
+ {t('customize.learningHint')}
+ </p>
+ {LEARNING_SURFACES.filter(
+ surface => !learningKinds || learningKinds.includes(surface.kind)
+ ).map(surface => (
+ <ChoiceRow
+ key={surface.kind}
+ label={t(surface.title)}
+ description={t(surface.description)}
+ checked={!draft.learning.hidden_features.includes(surface.kind)}
+ onChange={() =>
+ setDraft(previous => ({
+ ...previous,
+ learning: {
+ hidden_features: toggleHidden(
+ previous.learning.hidden_features,
+ surface.kind
+ ),
+ },
+ }))
+ }
+ />
+ ))}
+ </div>
+ )}
+ </>
+ )}
+ </Dialog>
+ )
+}
diff --git a/web/components/learning/LearningCreateMenu.tsx b/web/components/learning/LearningCreateMenu.tsx
index 6b336ca67..78239f6a0 100644
--- a/web/components/learning/LearningCreateMenu.tsx
+++ b/web/components/learning/LearningCreateMenu.tsx
@@ -1,70 +1,27 @@
'use client'
-import { useState } from 'react'
-import { useRouter } from 'next/navigation'
+import Link from 'next/link'
import { Plus } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import Tooltip from '@/shared/ui/Tooltip'
-import { Dialog } from '@/shared/ui/Dialog'
-import { LEARNING_SURFACES } from './surfaces'
-import { useAuthStatus } from '@/hooks/useAuthStatus'
-import { navigateTask } from '@/lib/workspace-scope'
import { pageActionClass } from '@/components/layout/FeaturePage'
import { useSidebarDrawer } from '@/components/layout/AppShell'
+import { scopedUrl, activeWorkspaceId } from '@/lib/workspace-scope'
+/** All creation entry points share a bookmarkable page instead of a transient menu. */
export function LearningCreateMenu({ compact = false }: { compact?: boolean }) {
const { t } = useTranslation()
- const router = useRouter()
const drawer = useSidebarDrawer()
- const [open, setOpen] = useState(false)
- const { learningPolicy } = useAuthStatus()
- const surfaces = LEARNING_SURFACES.filter(
- item =>
- !learningPolicy ||
- learningPolicy.allowedSurfaces.includes(
- item.kind === 'mastery' || item.kind === 'practice' ? 'chat' : item.kind
- )
- )
return (
- <>
- <Tooltip label={t('navigation.createLearning')} suppressed={open}>
- <button
- type="button"
- aria-label={t('navigation.createLearning')}
- onClick={() => setOpen(true)}
- className={compact ? 'dt-nav-icon' : pageActionClass()}
- >
- <Plus size={compact ? 17 : 15} />
- {!compact && t('navigation.createLearning')}
- </button>
- </Tooltip>
- <Dialog
- open={open}
- onClose={() => setOpen(false)}
- title={t('navigation.createLearning')}
- description={t('navigation.createLearningDescription')}
- closeLabel={t('Close')}
+ <Tooltip label={t('navigation.createLearning')}>
+ <Link
+ href={scopedUrl('/learning/new', activeWorkspaceId())}
+ aria-label={t('navigation.createLearning')}
+ onClick={() => drawer?.close()}
+ className={compact ? 'dt-nav-icon' : pageActionClass()}
>
- <div className="grid grid-cols-2 gap-3">
- {surfaces.map(item => (
- <button
- key={item.kind}
- type="button"
- className="rounded-xl border border-border p-4 text-left transition-colors hover:bg-muted/60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"
- onClick={() => {
- setOpen(false)
- drawer?.close()
- navigateTask(`${item.href}?create=1`, router.push)
- }}
- >
- <item.icon size={22} strokeWidth={1.6} className="mb-3 text-muted-foreground" />
- <span className="block text-sm font-medium">{t(item.title)}</span>
- <span className="mt-1 block text-xs leading-relaxed text-muted-foreground">
- {t(item.description)}
- </span>
- </button>
- ))}
- </div>
- </Dialog>
- </>
+ <Plus size={compact ? 17 : 15} />
+ {!compact && t('navigation.createLearning')}
+ </Link>
+ </Tooltip>
)
}
diff --git a/web/components/learning/NewLearningPage.tsx b/web/components/learning/NewLearningPage.tsx
new file mode 100644
index 000000000..b5ed84f1d
--- /dev/null
+++ b/web/components/learning/NewLearningPage.tsx
@@ -0,0 +1,111 @@
+'use client'
+
+import { useRouter } from 'next/navigation'
+import { ArrowUpRight, Plus, Settings2 } from 'lucide-react'
+import { m, useReducedMotion } from 'framer-motion'
+import { useTranslation } from 'react-i18next'
+import { useAuthStatus } from '@/hooks/useAuthStatus'
+import { useModules } from '@/hooks/useModules'
+import { usePageCustomization } from '@/context/PageCustomizationContext'
+import { PageCustomizeButton } from '@/components/customization/PageCustomizeButton'
+import { navigateTask } from '@/lib/workspace-scope'
+import { LEARNING_SURFACES } from './surfaces'
+import {
+ LearningShell,
+ LearningSkeleton,
+ LearningErrorState,
+ LearningEmptyState,
+} from './LearningShell'
+
+export default function NewLearningPage() {
+ const { t } = useTranslation()
+ const router = useRouter()
+ const reduced = useReducedMotion()
+ const auth = useAuthStatus()
+ const inventory = useModules()
+ const preferences = usePageCustomization()
+ const eligible = LEARNING_SURFACES.filter(
+ item =>
+ inventory.available(item.href) &&
+ (!auth.learningPolicy ||
+ auth.learningPolicy.allowedSurfaces.includes(
+ item.kind === 'mastery' || item.kind === 'practice' ? 'chat' : item.kind
+ ))
+ )
+ const surfaces = eligible.filter(
+ item => !preferences.value.learning.hidden_features.includes(item.kind)
+ )
+ const learningKinds = eligible.map(item => item.kind)
+ const loading = auth.loading || preferences.loading || (!inventory.modules && !inventory.error)
+ return (
+ <LearningShell
+ title={t('navigation.createLearning')}
+ subtitle={t('navigation.createLearningDescription')}
+ icon={Plus}
+ back={false}
+ action={<PageCustomizeButton page="learning" learningKinds={learningKinds} />}
+ >
+ {(inventory.error || preferences.error) && (
+ <LearningErrorState
+ message={t('customize.loadError')}
+ onRetry={() => {
+ inventory.reload()
+ preferences.reload()
+ }}
+ />
+ )}
+ {loading ? (
+ <LearningSkeleton count={4} />
+ ) : surfaces.length ? (
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:gap-5">
+ {surfaces.map((item, index) => (
+ <m.div
+ key={item.kind}
+ initial={reduced ? false : { opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: reduced ? 0 : 0.22, delay: reduced ? 0 : index * 0.04 }}
+ >
+ <button
+ type="button"
+ onClick={() => navigateTask(`${item.href}?create=1`, router.push)}
+ className="group flex h-full min-h-56 w-full flex-col rounded-2xl border border-border bg-card p-6 text-left shadow-sm transition-[border-color,box-shadow,transform] duration-200 hover:-translate-y-0.5 hover:border-primary/30 hover:shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring active:translate-y-0 motion-reduce:transform-none"
+ >
+ <span className="mb-6 flex w-full items-center justify-between">
+ <span
+ className={`inline-flex h-11 w-11 items-center justify-center rounded-xl ${item.accent}`}
+ >
+ <item.icon size={23} strokeWidth={1.6} />
+ </span>
+ <ArrowUpRight
+ size={18}
+ className="text-muted-foreground/50 transition-colors group-hover:text-foreground"
+ />
+ </span>
+ <span className="font-serif text-xl font-semibold tracking-tight">
+ {t(item.title)}
+ </span>
+ <span className="mt-2 max-w-md text-sm leading-relaxed text-muted-foreground">
+ {t(item.description)}
+ </span>
+ </button>
+ </m.div>
+ ))}
+ </div>
+ ) : (
+ !inventory.error && (
+ <LearningEmptyState
+ icon={<Settings2 size={28} />}
+ title={t('customize.emptyLearning')}
+ description={t('customize.emptyLearningHint')}
+ action={<PageCustomizeButton page="learning" learningKinds={learningKinds} />}
+ />
+ )
+ )}
+ {!loading && (
+ <p className="mt-6 text-xs leading-relaxed text-muted-foreground">
+ {t('customize.learningFooter')}
+ </p>
+ )}
+ </LearningShell>
+ )
+}
diff --git a/web/components/sidebar/LearningNavigation.tsx b/web/components/sidebar/LearningNavigation.tsx
index 9c696516a..a52e24b85 100644
--- a/web/components/sidebar/LearningNavigation.tsx
+++ b/web/components/sidebar/LearningNavigation.tsx
@@ -5,8 +5,7 @@ import { RecordGroups, RecordHeader, RecordTime, useRecordView } from './RecordL
import { useLayoutEffect, useState, type ReactNode } from 'react'
import Link from 'next/link'
import { usePathname, useSearchParams } from 'next/navigation'
-import { ChevronRight, LayoutGrid, MessageCircle } from 'lucide-react'
-import { LearningCreateMenu } from '@/components/learning/LearningCreateMenu'
+import { ChevronRight, LayoutGrid, MessageCircle, Plus } from 'lucide-react'
import { learningSurface } from '@/components/learning/surfaces'
import { allLearningActivity, fileLearningSessions, type LearningActivity } from '@/lib/learning-dashboard'
import { isNavigationTargetActive } from '@/lib/navigation'
@@ -89,11 +88,11 @@ export function LearningNavigation({
})
return (
<div className="dt-learning-navigation">
+ <OverviewRow href="/learning/new" label={t('navigation.createLearning')} icon={Plus} />
<OverviewRow
href="/learning"
label={t('navigation.allLearning')}
icon={LayoutGrid}
- action={<LearningCreateMenu compact />}
/>
<RecordHeader
title={t('navigation.learningRecords')}
diff --git a/web/components/sidebar/page-sections.ts b/web/components/sidebar/page-sections.ts
index 276e269c5..df411e9a7 100644
--- a/web/components/sidebar/page-sections.ts
+++ b/web/components/sidebar/page-sections.ts
@@ -1,5 +1,5 @@
import { CalendarDays } from 'lucide-react'
-import { Columns3, LayoutGrid, MessageCircle, PenLine, type LucideIcon } from 'lucide-react'
+import { Columns3, LayoutGrid, MessageCircle, PenLine, Plus, type LucideIcon } from 'lucide-react'
import {
HomeShelfIcon,
LearningShelfIcon,
@@ -76,6 +76,7 @@ export function pageSections({
label: t('navigation.learning'),
icon: LearningShelfIcon,
pages: [
+ { href: '/learning/new', label: t('navigation.createLearning'), icon: Plus },
{ href: '/learning', label: t('navigation.allLearning'), icon: LayoutGrid },
...LEARNING_SURFACES.filter(surface => surfaceAllowed(surface.kind)).map(surface => ({
href: surface.href,
diff --git a/web/context/PageCustomizationContext.tsx b/web/context/PageCustomizationContext.tsx
new file mode 100644
index 000000000..e19f370d5
--- /dev/null
+++ b/web/context/PageCustomizationContext.tsx
@@ -0,0 +1,101 @@
+'use client'
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react'
+import { apiFetch, apiUrl } from '@/lib/api'
+import { DEFAULT_PAGE_CUSTOMIZATION, type PageCustomization } from '@/lib/page-customization'
+
+interface PageCustomizationState {
+ value: PageCustomization
+ loading: boolean
+ error: boolean
+ reload: () => void
+ save: <K extends keyof PageCustomization>(
+ section: K,
+ value: PageCustomization[K]
+ ) => Promise<void>
+}
+const Context = createContext<PageCustomizationState>({
+ value: DEFAULT_PAGE_CUSTOMIZATION,
+ loading: false,
+ error: false,
+ reload: () => {},
+ save: async () => {
+ throw new Error('Page customization provider missing')
+ },
+})
+
+/** Account-scoped API persistence; no private prompts cached in browser storage. */
+export function PageCustomizationProvider({ children }: { children: ReactNode }) {
+ const [value, setValue] = useState(DEFAULT_PAGE_CUSTOMIZATION)
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState(false)
+ const revision = useRef(0)
+ const mounted = useRef(true)
+ const reload = useCallback(() => {
+ const request = ++revision.current
+ void apiFetch(apiUrl('/api/settings/page-customization'), {
+ cache: 'no-store',
+ signal: AbortSignal.timeout(15000),
+ })
+ .then(async response => {
+ if (!response.ok) throw new Error('Could not load page customization')
+ const next = (await response.json()) as PageCustomization
+ if (mounted.current && revision.current === request) {
+ setValue(next)
+ setError(false)
+ }
+ })
+ .catch(() => {
+ if (mounted.current && revision.current === request) setError(true)
+ })
+ .finally(() => {
+ if (mounted.current && revision.current === request) setLoading(false)
+ })
+ }, [])
+ useEffect(() => {
+ mounted.current = true
+ reload()
+ window.addEventListener('focus', reload)
+ return () => {
+ mounted.current = false
+ window.removeEventListener('focus', reload)
+ }
+ }, [reload])
+ const save = useCallback(
+ async <K extends keyof PageCustomization>(section: K, next: PageCustomization[K]) => {
+ ++revision.current // A stale GET must not overwrite a successful save.
+ const response = await apiFetch(apiUrl(`/api/settings/page-customization/${section}`), {
+ method: 'PUT',
+ signal: AbortSignal.timeout(15000),
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(next),
+ })
+ if (!response.ok) throw new Error('Could not save page customization')
+ const saved = (await response.json()) as PageCustomization
+ if (mounted.current) {
+ ++revision.current
+ setValue(saved)
+ setError(false)
+ setLoading(false)
+ }
+ },
+ []
+ )
+ const state = useMemo(
+ () => ({ value, loading, error, reload, save }),
+ [value, loading, error, reload, save]
+ )
+ return <Context.Provider value={state}>{children}</Context.Provider>
+}
+export function usePageCustomization() {
+ return useContext(Context)
+}
diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsx
index e42fa8c41..eb98ca54d 100644
--- a/web/features/chat/components/ChatWorkspace.tsx
+++ b/web/features/chat/components/ChatWorkspace.tsx
@@ -42,6 +42,7 @@ import {
SESSION_LOAD_TIMEOUT_MS,
shouldSurfaceLoadFailure,
} from "@/lib/session-load";
+import { PageCustomizeButton } from "@/components/customization/PageCustomizeButton";
import StarterSuggestions from "@/components/chat/home/StarterSuggestions";
// Imported eagerly so the drawer shell is always mounted off-screen —
// clicking a chip becomes a single CSS class flip, no chunk fetch + double
@@ -2558,6 +2559,7 @@ export default function ChatWorkspace() {
) : null}
</PageBarSlot>
<PageBarSlot name="actions" className="flex shrink-0 items-center gap-0.5">
+ <PageCustomizeButton page="chat" capabilities={visibleCapabilities} compact />
<HeaderActionButton
onClick={() => viewerPanelRef.current?.openMarkdownNoteTab()}
icon={NotebookPen}
@@ -2768,6 +2770,7 @@ export default function ChatWorkspace() {
</div>
) : null}
<ChatComposer
+ customizable
composerRef={composerRef}
capMenuRef={capMenuRef}
capBtnRef={capBtnRef}
diff --git a/web/lib/page-customization.ts b/web/lib/page-customization.ts
new file mode 100644
index 000000000..b54934966
--- /dev/null
+++ b/web/lib/page-customization.ts
@@ -0,0 +1,51 @@
+import type { TFunction } from 'i18next'
+
+export const STARTER_GROUPS = ['explain', 'solve', 'practice', 'plan', 'research'] as const
+export type StarterGroup = (typeof STARTER_GROUPS)[number]
+export interface StarterPrompt {
+ label: string
+ prompt: string
+}
+export interface ComposerControls {
+ skills: boolean
+ mcp: boolean
+ partners: boolean
+ preferences: boolean
+ voice: boolean
+}
+export interface ChatPageCustomization {
+ hidden_modes: string[]
+ controls: ComposerControls
+ starters: Partial<Record<StarterGroup, StarterPrompt[]>>
+}
+export interface LearningPageCustomization {
+ hidden_features: string[]
+}
+export interface PageCustomization {
+ chat: ChatPageCustomization
+ learning: LearningPageCustomization
+}
+export const DEFAULT_PAGE_CUSTOMIZATION: PageCustomization = {
+ chat: {
+ hidden_modes: [],
+ controls: { skills: true, mcp: true, partners: true, preferences: true, voice: true },
+ starters: {},
+ },
+ learning: { hidden_features: [] },
+}
+export function starterPrompts(
+ chat: ChatPageCustomization,
+ group: StarterGroup,
+ t: TFunction
+): StarterPrompt[] {
+ return (
+ chat.starters[group] ??
+ [1, 2, 3, 4].map(n => ({
+ label: t(`starters.${group}.${n}`),
+ prompt: t(`starters.${group}.${n}.prompt`),
+ }))
+ )
+}
+export function toggleHidden(values: string[], value: string): string[] {
+ return values.includes(value) ? values.filter(item => item !== value) : [...values, value]
+}
diff --git a/web/locales/de/app.json b/web/locales/de/app.json
index 6f7f2c347..9f7a105ca 100644
--- a/web/locales/de/app.json
+++ b/web/locales/de/app.json
@@ -6174,5 +6174,31 @@
"Modules": "Modules",
"Module": "Module",
"Stop DeepTutor before changing modules. Removing a module keeps your data.": "Stop DeepTutor before changing modules. Removing a module keeps your data.",
- "This module is not installed or is disabled.": "This module is not installed or is disabled."
+ "This module is not installed or is disabled.": "This module is not installed or is disabled.",
+ "customize.title": "Seite anpassen",
+ "customize.description": "Wähle die angezeigten Inhalte. Lernverlauf und installierte Module bleiben erhalten.",
+ "customize.reset": "Standard wiederherstellen",
+ "customize.sections": "Anpassungsbereiche",
+ "customize.modes": "Modi",
+ "customize.controls": "Eingabewerkzeuge",
+ "customize.starters": "Startvorlagen",
+ "customize.modesHint": "Wähle die verfügbaren Modi im Menü. Bestehende Gespräche behalten ihren aktuellen Modus.",
+ "customize.control.skills": "Skills",
+ "customize.control.mcp": "MCP-Verbindungen",
+ "customize.control.partners": "Partner",
+ "customize.control.preferences": "Präferenzen",
+ "customize.control.voice": "Spracheingabe",
+ "customize.promptLabel": "Angezeigter Titel",
+ "customize.promptText": "Text für das Eingabefeld",
+ "customize.removePrompt": "Vorlage entfernen",
+ "customize.addPrompt": "Vorlage hinzufügen",
+ "customize.resetGroup": "Kategorie zurücksetzen",
+ "customize.emptyPrompts": "Diese Kategorie bleibt ausgeblendet, bis du eine Vorlage hinzufügst.",
+ "customize.requiredPrompts": "Gib jeder Vorlage vor dem Speichern einen Titel und Inhalt.",
+ "customize.saveError": "Änderungen konnten nicht gespeichert werden. Dein Entwurf bleibt erhalten; versuche es erneut.",
+ "customize.loadError": "Seiteneinstellungen konnten nicht geladen werden. Bitte erneut versuchen.",
+ "customize.learningHint": "Wähle die Lernmethoden auf dieser Seite. Ausgeblendete Methoden lassen sich jederzeit wieder hinzufügen.",
+ "customize.emptyLearning": "Bereite dein nächstes Lernziel vor",
+ "customize.emptyLearningHint": "Passe diese Seite an, um Lernmethoden anzuzeigen. Nicht verfügbare Module findest du unter Einstellungen → Laufzeit.",
+ "customize.learningFooter": "Deine Auswahl wird in deinem Konto gespeichert. Es werden nur verfügbare Lernmethoden angezeigt."
}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index c587ff948..dd05c905a 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -6174,5 +6174,31 @@
"Modules": "Modules",
"Module": "Module",
"Stop DeepTutor before changing modules. Removing a module keeps your data.": "Stop DeepTutor before changing modules. Removing a module keeps your data.",
- "This module is not installed or is disabled.": "This module is not installed or is disabled."
+ "This module is not installed or is disabled.": "This module is not installed or is disabled.",
+ "customize.title": "Customize page",
+ "customize.description": "Choose what appears here. Your learning history and installed modules stay intact.",
+ "customize.reset": "Restore defaults",
+ "customize.sections": "Customization sections",
+ "customize.modes": "Modes",
+ "customize.controls": "Input tools",
+ "customize.starters": "Starting prompts",
+ "customize.modesHint": "Choose which available modes appear in the menu. Existing conversations keep their current mode.",
+ "customize.control.skills": "Skills",
+ "customize.control.mcp": "MCP connectors",
+ "customize.control.partners": "Partners",
+ "customize.control.preferences": "Preferences",
+ "customize.control.voice": "Voice input",
+ "customize.promptLabel": "Display title",
+ "customize.promptText": "Prompt inserted into the input",
+ "customize.removePrompt": "Remove prompt",
+ "customize.addPrompt": "Add prompt",
+ "customize.resetGroup": "Restore this category",
+ "customize.emptyPrompts": "This category is hidden until you add a prompt.",
+ "customize.requiredPrompts": "Give every prompt a title and content before saving.",
+ "customize.saveError": "Could not save your changes. Your draft is still here; please retry.",
+ "customize.loadError": "Could not load page settings. Retry to continue.",
+ "customize.learningHint": "Choose the learning methods shown on this page. Hidden methods can be added back at any time.",
+ "customize.emptyLearning": "Make room for your next learning goal",
+ "customize.emptyLearningHint": "Customize this page to show learning methods. Unavailable modules can be reviewed in Settings → Runtime.",
+ "customize.learningFooter": "Your choices are saved to your account. Only learning methods available in this environment are shown."
}
diff --git a/web/locales/fr/app.json b/web/locales/fr/app.json
index f72495d7f..b84a8a78b 100644
--- a/web/locales/fr/app.json
+++ b/web/locales/fr/app.json
@@ -6328,5 +6328,31 @@
"Modules": "Modules",
"Module": "Module",
"Stop DeepTutor before changing modules. Removing a module keeps your data.": "Stop DeepTutor before changing modules. Removing a module keeps your data.",
- "This module is not installed or is disabled.": "This module is not installed or is disabled."
+ "This module is not installed or is disabled.": "This module is not installed or is disabled.",
+ "customize.title": "Personnaliser la page",
+ "customize.description": "Choisissez les éléments affichés. Votre historique et les modules installés sont conservés.",
+ "customize.reset": "Rétablir les valeurs par défaut",
+ "customize.sections": "Rubriques de personnalisation",
+ "customize.modes": "Modes",
+ "customize.controls": "Outils de saisie",
+ "customize.starters": "Suggestions de départ",
+ "customize.modesHint": "Choisissez les modes disponibles dans le menu. Les conversations existantes conservent leur mode actuel.",
+ "customize.control.skills": "Compétences",
+ "customize.control.mcp": "Connecteurs MCP",
+ "customize.control.partners": "Partenaires",
+ "customize.control.preferences": "Préférences",
+ "customize.control.voice": "Saisie vocale",
+ "customize.promptLabel": "Titre affiché",
+ "customize.promptText": "Texte inséré dans le champ de saisie",
+ "customize.removePrompt": "Supprimer la suggestion",
+ "customize.addPrompt": "Ajouter une suggestion",
+ "customize.resetGroup": "Rétablir cette catégorie",
+ "customize.emptyPrompts": "Cette catégorie reste masquée tant que vous n’ajoutez pas de suggestion.",
+ "customize.requiredPrompts": "Renseignez le titre et le contenu de chaque suggestion avant d’enregistrer.",
+ "customize.saveError": "Impossible d’enregistrer. Votre brouillon est conservé ; veuillez réessayer.",
+ "customize.loadError": "Impossible de charger les paramètres de la page. Veuillez réessayer.",
+ "customize.learningHint": "Choisissez les méthodes d’apprentissage affichées. Vous pouvez rétablir les méthodes masquées à tout moment.",
+ "customize.emptyLearning": "Préparez votre prochain objectif d’apprentissage",
+ "customize.emptyLearningHint": "Personnalisez cette page pour afficher les méthodes. Consultez les modules indisponibles dans Paramètres → Exécution.",
+ "customize.learningFooter": "Vos choix sont enregistrés dans votre compte. Seules les méthodes disponibles sont affichées."
}
diff --git a/web/locales/pl/app.json b/web/locales/pl/app.json
index 13bd6efcb..edb59bd88 100644
--- a/web/locales/pl/app.json
+++ b/web/locales/pl/app.json
@@ -6196,5 +6196,31 @@
"Modules": "Modules",
"Module": "Module",
"Stop DeepTutor before changing modules. Removing a module keeps your data.": "Stop DeepTutor before changing modules. Removing a module keeps your data.",
- "This module is not installed or is disabled.": "This module is not installed or is disabled."
+ "This module is not installed or is disabled.": "This module is not installed or is disabled.",
+ "customize.title": "Dostosuj stronę",
+ "customize.description": "Wybierz widoczne elementy. Historia nauki i zainstalowane moduły pozostaną zachowane.",
+ "customize.reset": "Przywróć domyślne",
+ "customize.sections": "Sekcje dostosowania",
+ "customize.modes": "Tryby",
+ "customize.controls": "Narzędzia wprowadzania",
+ "customize.starters": "Podpowiedzi na start",
+ "customize.modesHint": "Wybierz dostępne tryby wyświetlane w menu. Istniejące rozmowy zachowają bieżący tryb.",
+ "customize.control.skills": "Umiejętności",
+ "customize.control.mcp": "Połączenia MCP",
+ "customize.control.partners": "Partnerzy",
+ "customize.control.preferences": "Preferencje",
+ "customize.control.voice": "Wprowadzanie głosowe",
+ "customize.promptLabel": "Wyświetlany tytuł",
+ "customize.promptText": "Treść wstawiana do pola wiadomości",
+ "customize.removePrompt": "Usuń podpowiedź",
+ "customize.addPrompt": "Dodaj podpowiedź",
+ "customize.resetGroup": "Przywróć kategorię",
+ "customize.emptyPrompts": "Ta kategoria jest ukryta, dopóki nie dodasz podpowiedzi.",
+ "customize.requiredPrompts": "Przed zapisaniem uzupełnij tytuł i treść każdej podpowiedzi.",
+ "customize.saveError": "Nie udało się zapisać zmian. Szkic został zachowany; spróbuj ponownie.",
+ "customize.loadError": "Nie udało się wczytać ustawień strony. Spróbuj ponownie.",
+ "customize.learningHint": "Wybierz metody nauki na tej stronie. Ukryte metody możesz przywrócić w dowolnej chwili.",
+ "customize.emptyLearning": "Przygotuj się na kolejny cel nauki",
+ "customize.emptyLearningHint": "Dostosuj stronę, aby wyświetlić metody nauki. Niedostępne moduły sprawdzisz w Ustawienia → Środowisko uruchomieniowe.",
+ "customize.learningFooter": "Twój wybór zostanie zapisany na koncie. Wyświetlane są tylko dostępne metody nauki."
}
diff --git a/web/locales/uk/app.json b/web/locales/uk/app.json
index d1ac0bbbe..ee57868b6 100644
--- a/web/locales/uk/app.json
+++ b/web/locales/uk/app.json
@@ -6196,5 +6196,31 @@
"Modules": "Modules",
"Module": "Module",
"Stop DeepTutor before changing modules. Removing a module keeps your data.": "Stop DeepTutor before changing modules. Removing a module keeps your data.",
- "This module is not installed or is disabled.": "This module is not installed or is disabled."
+ "This module is not installed or is disabled.": "This module is not installed or is disabled.",
+ "customize.title": "Налаштувати сторінку",
+ "customize.description": "Виберіть видимі елементи. Історія навчання та встановлені модулі збережуться.",
+ "customize.reset": "Відновити типові налаштування",
+ "customize.sections": "Розділи налаштування",
+ "customize.modes": "Режими",
+ "customize.controls": "Інструменти введення",
+ "customize.starters": "Початкові підказки",
+ "customize.modesHint": "Виберіть доступні режими меню. Наявні розмови збережуть поточний режим.",
+ "customize.control.skills": "Навички",
+ "customize.control.mcp": "З’єднання MCP",
+ "customize.control.partners": "Партнери",
+ "customize.control.preferences": "Уподобання",
+ "customize.control.voice": "Голосове введення",
+ "customize.promptLabel": "Заголовок для показу",
+ "customize.promptText": "Текст для поля введення",
+ "customize.removePrompt": "Видалити підказку",
+ "customize.addPrompt": "Додати підказку",
+ "customize.resetGroup": "Відновити категорію",
+ "customize.emptyPrompts": "Ця категорія прихована, доки ви не додасте підказку.",
+ "customize.requiredPrompts": "Перед збереженням заповніть заголовок і текст кожної підказки.",
+ "customize.saveError": "Не вдалося зберегти зміни. Чернетку збережено; спробуйте ще раз.",
+ "customize.loadError": "Не вдалося завантажити налаштування сторінки. Спробуйте ще раз.",
+ "customize.learningHint": "Виберіть методи навчання на цій сторінці. Приховані методи можна повернути будь-коли.",
+ "customize.emptyLearning": "Підготуйтеся до наступної навчальної мети",
+ "customize.emptyLearningHint": "Налаштуйте сторінку, щоб показати методи навчання. Недоступні модулі можна переглянути в Налаштування → Середовище виконання.",
+ "customize.learningFooter": "Ваш вибір зберігається в обліковому записі. Показано лише доступні методи навчання."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index dda0d7704..6a3c1deaa 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -6174,5 +6174,31 @@
"Modules": "模块",
"Module": "模块",
"Stop DeepTutor before changing modules. Removing a module keeps your data.": "更改模块前请停止 DeepTutor。卸载模块会保留你的数据。",
- "This module is not installed or is disabled.": "此模块尚未安装或已禁用。"
+ "This module is not installed or is disabled.": "此模块尚未安装或已禁用。",
+ "customize.title": "自定义页面",
+ "customize.description": "选择页面中显示的内容,已有学习记录和已安装模块会保留。",
+ "customize.reset": "恢复默认",
+ "customize.sections": "自定义分类",
+ "customize.modes": "模式",
+ "customize.controls": "输入工具",
+ "customize.starters": "起始提示",
+ "customize.modesHint": "选择模式菜单中显示的功能。已有对话会保留当前模式。",
+ "customize.control.skills": "技能",
+ "customize.control.mcp": "MCP 连接器",
+ "customize.control.partners": "伙伴",
+ "customize.control.preferences": "偏好",
+ "customize.control.voice": "语音输入",
+ "customize.promptLabel": "显示标题",
+ "customize.promptText": "填入输入框的提示内容",
+ "customize.removePrompt": "移除提示",
+ "customize.addPrompt": "添加提示",
+ "customize.resetGroup": "恢复此分类",
+ "customize.emptyPrompts": "此分类暂无提示,添加后会重新显示在聊天页。",
+ "customize.requiredPrompts": "请为每条提示填写标题和内容后再保存。",
+ "customize.saveError": "未能保存修改,草稿已保留,请重试。",
+ "customize.loadError": "未能加载页面设置,请重试。",
+ "customize.learningHint": "选择在新建学习页显示的学习方式。隐藏后可以随时重新添加。",
+ "customize.emptyLearning": "为下一次学习做好准备",
+ "customize.emptyLearningHint": "通过自定义页面添加学习方式。未安装或已禁用的模块可在设置 → 运行时中查看。",
+ "customize.learningFooter": "自定义设置会保存到你的账户;此处仅显示当前环境中可用的学习方式。"
}
diff --git a/web/scripts/i18n_audit.mjs b/web/scripts/i18n_audit.mjs
index c8476e4ba..703ff38d3 100644
--- a/web/scripts/i18n_audit.mjs
+++ b/web/scripts/i18n_audit.mjs
@@ -133,7 +133,7 @@ function reportUntranslatedKeys() {
}
const locales = new Set(REQUIRED_LOCALES);
for (const ent of fs.readdirSync(localeDir, { withFileTypes: true })) {
- if (ent.isDirectory()) locales.add(ent.name);
+ if (ent.isDirectory() && !ent.name.startsWith(".")) locales.add(ent.name);
}
const known = new Map();
diff --git a/web/tests/page-customization.spec.tsx b/web/tests/page-customization.spec.tsx
new file mode 100644
index 000000000..06ff924ae
--- /dev/null
+++ b/web/tests/page-customization.spec.tsx
@@ -0,0 +1,156 @@
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, expect, it, vi } from 'vitest'
+import { MessageSquare, Microscope } from 'lucide-react'
+import { initI18n } from '@/i18n/init'
+import PageCustomizeDialog from '@/components/customization/PageCustomizeDialog'
+import { DEFAULT_PAGE_CUSTOMIZATION, type PageCustomization } from '@/lib/page-customization'
+import StarterSuggestions from '@/components/chat/home/StarterSuggestions'
+import NewLearningPage from '@/components/learning/NewLearningPage'
+
+initI18n('en')
+const harness = vi.hoisted(() => ({
+ save: vi.fn(),
+ value: null as PageCustomization | null,
+ navigate: vi.fn(),
+ available: vi.fn(),
+ allowed: null as string[] | null,
+}))
+vi.mock('@/context/PageCustomizationContext', () => ({
+ usePageCustomization: () => ({
+ value: harness.value,
+ save: harness.save,
+ loading: false,
+ error: false,
+ }),
+}))
+vi.mock('@/lib/api', () => ({
+ apiUrl: (url: string) => url,
+ apiFetch: vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ suggestions: [], stale: false, status: 'no-material' }),
+ })),
+}))
+vi.mock('@/components/customization/PageCustomizeButton', () => ({
+ PageCustomizeButton: () => <button>Customize page</button>,
+}))
+vi.mock('@/hooks/useAuthStatus', () => ({
+ useAuthStatus: () => ({
+ loading: false,
+ learningPolicy: harness.allowed ? { allowedSurfaces: harness.allowed } : null,
+ }),
+}))
+vi.mock('@/hooks/useModules', () => ({
+ useModules: () => ({ modules: [], available: harness.available, error: false }),
+}))
+vi.mock('next/navigation', () => ({
+ usePathname: () => '/learning/new',
+ useRouter: () => ({ push: vi.fn() }),
+ useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('@/lib/workspace-scope', () => ({
+ activeWorkspaceId: () => 'workspace-a',
+ scopedUrl: (url: string) => url,
+ navigateTask: harness.navigate,
+}))
+const capabilities = [
+ { value: '', label: 'Chat', description: 'Chat', icon: MessageSquare, allowedTools: [] },
+ {
+ value: 'deep_research',
+ label: 'Research',
+ description: 'Research',
+ icon: Microscope,
+ allowedTools: [],
+ },
+]
+beforeEach(() => {
+ harness.value = structuredClone(DEFAULT_PAGE_CUSTOMIZATION)
+ harness.save.mockResolvedValue(undefined)
+ harness.available.mockReturnValue(true)
+ harness.allowed = null
+})
+function dialog(close = vi.fn()) {
+ return render(
+ <PageCustomizeDialog
+ page="chat"
+ initial={harness.value!}
+ capabilities={capabilities}
+ onClose={close}
+ />
+ )
+}
+
+it('saves selected controls and modes without changing core chat', async () => {
+ const close = vi.fn()
+ dialog(close)
+ expect(screen.queryByRole('switch', { name: /^Chat/ })).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('switch', { name: /Research/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'Input tools' }))
+ fireEvent.click(screen.getByRole('switch', { name: 'Voice input' }))
+ fireEvent.click(screen.getByRole('switch', { name: 'MCP connectors' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(close).toHaveBeenCalled())
+ expect(harness.save).toHaveBeenCalledWith(
+ 'chat',
+ expect.objectContaining({
+ hidden_modes: ['deep_research'],
+ controls: expect.objectContaining({ voice: false, mcp: false, skills: true }),
+ })
+ )
+})
+it('edits prompt titles/content, adds, removes, and restores the translated defaults', () => {
+ dialog()
+ fireEvent.click(screen.getByRole('button', { name: 'Starting prompts' }))
+ fireEvent.change(screen.getByRole('textbox', { name: 'Display title 1' }), {
+ target: { value: 'My starter' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Add prompt' }))
+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Remove prompt 5' }))
+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Restore this category' }))
+ expect(screen.getByRole('textbox', { name: 'Display title 1' })).not.toHaveValue('My starter')
+})
+it('keeps the draft on save failure and does not save on cancel', async () => {
+ const close = vi.fn()
+ harness.save.mockRejectedValueOnce(new Error('offline'))
+ dialog(close)
+ fireEvent.click(screen.getByRole('button', { name: 'Input tools' }))
+ fireEvent.click(screen.getByRole('switch', { name: 'Voice input' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await screen.findByRole('alert')
+ expect(screen.getByRole('switch', { name: 'Voice input' })).not.toBeChecked()
+ expect(close).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(close).toHaveBeenCalledOnce()
+ expect(harness.save).toHaveBeenCalledOnce()
+})
+it('uses custom starting prompts literally and hides an empty category', async () => {
+ harness.value!.chat.starters = {
+ explain: [{ label: 'Personal title', prompt: 'Private customized content' }],
+ solve: [],
+ }
+ const pick = vi.fn()
+ await act(async () => {
+ render(<StarterSuggestions onPick={pick} />)
+ })
+ expect(screen.queryByRole('button', { name: 'Solve' })).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Explain' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Personal title' }))
+ expect(pick).toHaveBeenCalledWith('Private customized content')
+})
+it('shows only selected learning methods that modules and account policy allow', () => {
+ harness.value!.learning.hidden_features = ['mastery']
+ harness.available.mockImplementation((path: string) => !path.includes('books'))
+ harness.allowed = ['chat', 'reading']
+ render(<NewLearningPage />)
+ expect(screen.queryByRole('button', { name: /Mastery Path/ })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /^Books/ })).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: /^Practice/ }))
+ expect(harness.navigate).toHaveBeenCalledWith('/learning/practice?create=1', expect.any(Function))
+})
+it('leaves a way to restore choices when every learning method is hidden', () => {
+ harness.value!.learning.hidden_features = ['books', 'mastery', 'practice', 'reading']
+ render(<NewLearningPage />)
+ expect(screen.getByText('Make room for your next learning goal')).toBeInTheDocument()
+ expect(screen.getAllByRole('button', { name: 'Customize page' })).toHaveLength(2)
+})