DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(settings): add reviewable named presets
XZH65f6f4a504fc
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 69ef55688..ec6e058cf 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -49,6 +49,11 @@ from deeptutor.services.config.settings_draft import (merge_draft_secrets,redact_draft,)+from deeptutor.services.config.settings_presets import (+ SETTINGS_PRESETS_SCHEMA_VERSION,+ get_settings_preset,+ list_settings_presets,+)from deeptutor.services.llm.config import clear_llm_config_cachefrom deeptutor.services.model_selection import list_llm_optionsfrom deeptutor.services.path_service import get_path_service@@ -224,6 +229,10 @@ class SettingsDraftPayload(BaseModel):extensions: dict[str, Any] = Field(default_factory=dict)+class SettingsPresetDraftRequest(SettingsDraftPayload):+ """The current draft envelope submitted alongside a named preset."""++class CodexReasoningEffortUpdate(BaseModel):model: str = Field(min_length=1)reasoning_effort: str | None = None@@ -1135,6 +1144,64 @@ async def get_settings_readiness():return await build_settings_readiness()[email protected]("/presets")+async def get_settings_presets():+ """List value-free starting points for a reviewable draft."""++ _require_settings_admin()+ return {+ "schema_version": SETTINGS_PRESETS_SCHEMA_VERSION,+ "presets": list_settings_presets(),+ }+++async def _stage_settings_preset(+ preset_id: str,+ payload: SettingsPresetDraftRequest,+) -> dict[str, Any]:+ """Merge one preset into the unapplied draft; never touch live settings."""++ preset = get_settings_preset(preset_id)+ if preset is None:+ raise HTTPException(status.HTTP_404_NOT_FOUND, f"Unknown preset '{preset_id}'.")++ draft_service = get_settings_draft_service()+ stored = draft_service.load()+ incoming = payload.model_dump()++ # The browser sends its whole envelope, so unrelated unsaved edits survive.+ # When a caller omits extensions, existing extension drafts must survive too.+ extensions = deepcopy(stored.get("extensions") or {})+ extensions.update(deepcopy(incoming.get("extensions") or {}))+ incoming["extensions"] = extensions++ merged = merge_draft_secrets(+ incoming,+ stored,+ get_model_catalog_service().load(),+ )+ preset_draft = preset.draft_extensions()+ tools = preset_draft.get("enabled_tools", {}).get("enabled_tools", [])+ preset_draft["enabled_tools"]["enabled_tools"] = sanitize_enabled_tools(tools)+ merged["extensions"].update(preset_draft)++ return {+ "preset": preset.public_dict(),+ "draft": redact_draft(draft_service.save(merged)),+ }++[email protected]("/presets/{preset_id}/draft")+async def stage_settings_preset(+ preset_id: str,+ payload: SettingsPresetDraftRequest,+) -> dict[str, Any]:+ """Load a named preset into the existing draft for review."""++ _require_settings_admin()+ return await _stage_settings_preset(preset_id, payload)++@router.put("/document-parsing")async def update_document_parsing_settings(payload: DocumentParsingUpdate):_require_settings_admin()diff --git a/deeptutor/services/config/settings_presets.py b/deeptutor/services/config/settings_presets.pynew file mode 100644index 000000000..bca500334--- /dev/null+++ b/deeptutor/services/config/settings_presets.py@@ -0,0 +1,135 @@+"""Value-free named Settings presets.++A preset describes a reviewable starting point. It carries stable identifiers+and draft payloads only: no credentials, deployment endpoints, provider+profiles, or write side effects. Staging one deliberately uses the ordinary+Settings draft, so the user still sees and applies every change.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++SETTINGS_PRESETS_SCHEMA_VERSION = "deeptutor.settings-presets/v1"++_DOCUMENT_PARSING_EXTENSION = "document_parsing"+_ENABLED_TOOLS_EXTENSION = "enabled_tools"+++@dataclass(frozen=True, slots=True)+class SettingsPreset:+ """One static preset and the draft payload it can stage."""++ id: str+ label: str+ description: str+ resource_cost: str+ credentials: tuple[str, ...]+ prerequisites: tuple[str, ...]+ unlocked_features: tuple[str, ...]+ parser_engine: str+ tools: tuple[str, ...]++ def public_dict(self) -> dict[str, Any]:+ """Return the wire shape without the implementation-only write payload."""++ return {+ "id": self.id,+ "label": self.label,+ "description": self.description,+ "parser": self.parser_engine,+ "resource_cost": self.resource_cost,+ "credentials": list(self.credentials),+ "prerequisites": list(self.prerequisites),+ "unlocked_features": list(self.unlocked_features),+ }++ def draft_extensions(self) -> dict[str, dict[str, Any]]:+ """Return payload shapes accepted by the existing draft apply flow."""++ return {+ _DOCUMENT_PARSING_EXTENSION: {"engine": self.parser_engine},+ _ENABLED_TOOLS_EXTENSION: {"enabled_tools": list(self.tools)},+ }+++_PRESETS: tuple[SettingsPreset, ...] = (+ SettingsPreset(+ id="basic_text",+ label="settings.presets.basic_text.name",+ description="settings.presets.basic_text.description",+ resource_cost="low",+ credentials=("llm",),+ prerequisites=("llm_profile",),+ unlocked_features=("core_chat", "reasoning"),+ parser_engine="text_only",+ tools=("brainstorm", "reason"),+ ),+ SettingsPreset(+ id="local_multimodal",+ label="settings.presets.local_multimodal.name",+ description="settings.presets.local_multimodal.description",+ resource_cost="medium",+ credentials=("llm", "imagegen", "videogen"),+ prerequisites=("llm_profile", "markdown_parser", "media_profiles"),+ unlocked_features=("document_parsing", "image_generation", "video_generation"),+ parser_engine="markitdown",+ tools=("brainstorm", "reason", "imagegen", "videogen"),+ ),+ SettingsPreset(+ id="university_study",+ label="settings.presets.university_study.name",+ description="settings.presets.university_study.description",+ resource_cost="medium",+ credentials=("llm",),+ prerequisites=("llm_profile", "markdown_parser", "search_profile"),+ unlocked_features=("document_parsing", "web_search", "paper_search", "reasoning"),+ parser_engine="markitdown",+ tools=("brainstorm", "web_search", "paper_search", "reason"),+ ),+ SettingsPreset(+ id="full_generation",+ label="settings.presets.full_generation.name",+ description="settings.presets.full_generation.description",+ resource_cost="high",+ credentials=("llm", "imagegen", "videogen"),+ prerequisites=("llm_profile", "markdown_parser", "media_profiles", "search_profile"),+ unlocked_features=(+ "document_parsing",+ "web_search",+ "paper_search",+ "image_generation",+ "video_generation",+ ),+ parser_engine="markitdown",+ tools=(+ "brainstorm",+ "web_search",+ "paper_search",+ "reason",+ "imagegen",+ "videogen",+ ),+ ),+)++_PRESETS_BY_ID = {preset.id: preset for preset in _PRESETS}+++def list_settings_presets() -> list[dict[str, Any]]:+ """Return the stable, review-only preset catalog."""++ return [preset.public_dict() for preset in _PRESETS]+++def get_settings_preset(preset_id: str) -> SettingsPreset | None:+ return _PRESETS_BY_ID.get(preset_id)+++__all__ = [+ "SETTINGS_PRESETS_SCHEMA_VERSION",+ "SettingsPreset",+ "get_settings_preset",+ "list_settings_presets",+]diff --git a/tests/api/test_settings_presets.py b/tests/api/test_settings_presets.pynew file mode 100644index 000000000..c07c4f491--- /dev/null+++ b/tests/api/test_settings_presets.py@@ -0,0 +1,119 @@+from __future__ import annotations++from copy import deepcopy+from pathlib import Path+from typing import Any++from fastapi import HTTPException+import pytest++from deeptutor.api.routers import settings as settings_router+from deeptutor.services.config.model_catalog import CATALOG_SECRET_MASK+from deeptutor.services.config.settings_draft import SettingsDraftService+++class _FakeCatalogService:+ def __init__(self, catalog: dict[str, Any]) -> None:+ self.catalog = deepcopy(catalog)++ def load(self) -> dict[str, Any]:+ return deepcopy(self.catalog)+++def _catalog(api_key: str) -> dict[str, Any]:+ return {+ "services": {+ "llm": {+ "active_profile_id": "p1",+ "profiles": [+ {+ "id": "p1",+ "name": "Review profile",+ "api_key": api_key,+ "models": [],+ }+ ],+ }+ }+ }+++async def test_staging_a_preset_writes_only_the_reviewable_draft(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ live = _catalog("sk-live")+ catalog_service = _FakeCatalogService(live)+ draft_path = tmp_path / "settings_draft.json"+ draft_service = SettingsDraftService(path=draft_path)+ stored = draft_service.save(+ {+ "catalog": _catalog(CATALOG_SECRET_MASK),+ "extensions": {"memory": {"enabled": False}},+ }+ )++ guarded = 0++ def guarded_admin() -> None:+ nonlocal guarded+ guarded += 1++ monkeypatch.setattr(+ settings_router,+ "get_model_catalog_service",+ lambda: catalog_service,+ )+ monkeypatch.setattr(+ settings_router,+ "get_settings_draft_service",+ lambda: draft_service,+ )+ monkeypatch.setattr(+ settings_router,+ "_require_settings_admin",+ guarded_admin,+ )++ request = settings_router.SettingsPresetDraftRequest(+ catalog=stored["catalog"],+ extensions={},+ )+ response = await settings_router.stage_settings_preset(+ "university_study",+ request,+ )++ assert guarded == 1+ assert response["preset"]["id"] == "university_study"+ draft = response["draft"]+ assert draft["extensions"]["document_parsing"] == {"engine": "markitdown"}+ assert draft["extensions"]["enabled_tools"] == {+ "enabled_tools": ["brainstorm", "web_search", "paper_search", "reason"]+ }+ assert draft["extensions"]["memory"] == {"enabled": False}+ assert draft["catalog"]["services"]["llm"]["profiles"][0]["api_key"] == (CATALOG_SECRET_MASK)++ saved = draft_service.load()+ assert saved["extensions"]["document_parsing"] == draft["extensions"]["document_parsing"]+ assert saved["catalog"]["services"]["llm"]["profiles"][0]["api_key"] == "sk-live"+ assert catalog_service.load() == _catalog("sk-live")+++async def test_an_unknown_preset_does_not_touch_the_draft(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ draft_service = SettingsDraftService(path=tmp_path / "settings_draft.json")+ monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: None)+ monkeypatch.setattr(settings_router, "get_settings_draft_service", lambda: draft_service)+ monkeypatch.setattr(settings_router, "_require_settings_admin", lambda: None)++ with pytest.raises(HTTPException) as raised:+ await settings_router.stage_settings_preset(+ "missing",+ settings_router.SettingsPresetDraftRequest(),+ )++ assert raised.value.status_code == 404+ assert not draft_service.path.exists()diff --git a/tests/services/config/test_settings_presets.py b/tests/services/config/test_settings_presets.pynew file mode 100644index 000000000..c1699065c--- /dev/null+++ b/tests/services/config/test_settings_presets.py@@ -0,0 +1,40 @@+from __future__ import annotations++from deeptutor.services.config.settings_presets import (+ SETTINGS_PRESETS_SCHEMA_VERSION,+ get_settings_preset,+ list_settings_presets,+)+++def test_the_settings_preset_catalog_is_stable_and_value_free() -> None:+ presets = list_settings_presets()++ assert [preset["id"] for preset in presets] == [+ "basic_text",+ "local_multimodal",+ "university_study",+ "full_generation",+ ]+ forbidden = ("api_key", "base_url", "password", "secret", "localhost")+ for preset in presets:+ rendered = repr(preset).lower()+ assert not any(value in rendered for value in forbidden)+ assert all(preset["parser"] for preset in presets)+++def test_a_preset_has_the_draft_payloads_the_apply_flow_already_writes() -> None:+ preset = get_settings_preset("university_study")+ assert preset is not None++ draft = preset.draft_extensions()++ assert draft["document_parsing"] == {"engine": "markitdown"}+ assert draft["enabled_tools"] == {+ "enabled_tools": ["brainstorm", "web_search", "paper_search", "reason"]+ }+++def test_unknown_presets_are_rejected_without_inventing_a_default() -> None:+ assert get_settings_preset("do-everything") is None+ assert SETTINGS_PRESETS_SCHEMA_VERSION == "deeptutor.settings-presets/v1"diff --git a/web/components/settings/SettingsOverview.tsx b/web/components/settings/SettingsOverview.tsxindex 368657acc..00d3fb281 100644--- a/web/components/settings/SettingsOverview.tsx+++ b/web/components/settings/SettingsOverview.tsx@@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next";import { apiFetch, apiUrl } from "@/lib/api";import SettingsReadinessPanel from "@/components/settings/SettingsReadinessPanel";+import SettingsPresetsPanel from "@/components/settings/SettingsPresetsPanel";import SettingsStatusPanel from "@/components/settings/SettingsStatusPanel";import { SettingRow, SettingSection } from "@/components/settings/shared";import { setPendingPrompt } from "@/lib/pending-prompt";@@ -153,6 +154,8 @@ export default function SettingsOverview() {<SettingsReadinessPanel enabled={catalogEditable === true} />+ {catalogEditable === true && <SettingsPresetsPanel enabled={true} />}+{apiBase && (<p className="mt-5 text-[11.5px] text-[var(--muted-foreground)]">{t("Browser API base")}{" "}diff --git a/web/components/settings/SettingsPresetsPanel.tsx b/web/components/settings/SettingsPresetsPanel.tsxnew file mode 100644index 000000000..d842d8bb4--- /dev/null+++ b/web/components/settings/SettingsPresetsPanel.tsx@@ -0,0 +1,181 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { Loader2, RefreshCcw } from "lucide-react";+import { useTranslation } from "react-i18next";++import {+ fetchSettingsPresets,+ type SettingsPreset,+} from "@/lib/settings-presets";+import { useSettings } from "@/features/settings/store/SettingsStore";++export default function SettingsPresetsPanel({ enabled }: { enabled: boolean }) {+ const { t } = useTranslation();+ const { stagePreset, saving } = useSettings();+ const [presets, setPresets] = useState<SettingsPreset[] | null>(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState(false);+ const [activeId, setActiveId] = useState<string | null>(null);++ const refresh = useCallback(async () => {+ setLoading(true);+ setError(false);+ try {+ const payload = await fetchSettingsPresets();+ setPresets(payload.presets);+ } catch {+ setError(true);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ if (!enabled) return;+ void refresh();+ }, [enabled, refresh]);++ const load = async (preset: SettingsPreset) => {+ if (saving) return;+ setActiveId(preset.id);+ try {+ await stagePreset(preset.id);+ } finally {+ setActiveId(null);+ }+ };++ return (+ <section className="mt-8" aria-labelledby="settings-presets-title">+ <header className="mb-2 flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h2+ id="settings-presets-title"+ className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]"+ >+ {t("settings.presets.title")}+ </h2>+ <p className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t("settings.presets.blurb")}+ </p>+ </div>+ <button+ type="button"+ onClick={() => void refresh()}+ disabled={loading || !enabled}+ aria-label={t("Refresh")}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[11.5px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:opacity-50"+ >+ {loading ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <RefreshCcw className="h-3 w-3" />+ )}+ {t("readiness.refresh")}+ </button>+ </header>++ {error && (+ <p role="alert" className="py-3 text-[12.5px] text-amber-600">+ {t("settings.presets.error")}+ </p>+ )}++ {!presets && !error && (+ <div className="grid gap-3 pt-2 sm:grid-cols-2">+ {[0, 1, 2, 3].map((index) => (+ <div+ key={index}+ className="h-[172px] animate-pulse rounded-lg border border-[var(--border)]/60 bg-[var(--muted)]/40"+ />+ ))}+ </div>+ )}++ {presets && presets.length === 0 && (+ <p className="py-3 text-[12.5px] text-[var(--muted-foreground)]">+ {t("settings.presets.empty")}+ </p>+ )}++ {presets && presets.length > 0 && (+ <div className="grid gap-3 pt-2 sm:grid-cols-2">+ {presets.map((preset) => (+ <article+ key={preset.id}+ className="flex min-w-0 flex-col rounded-lg border border-[var(--border)]/70 p-3"+ >+ <div className="flex min-w-0 items-start justify-between gap-3">+ <h3 className="min-w-0 text-[13px] font-medium text-[var(--foreground)]">+ {t(preset.label)}+ </h3>+ <span className="shrink-0 text-[11px] text-[var(--muted-foreground)]">+ {t(`settings.presets.cost.${preset.resource_cost}`)}+ </span>+ </div>+ <p className="mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t(preset.description)}+ </p>++ <dl className="mt-3 space-y-1.5 text-[11.5px]">+ <div className="flex flex-wrap items-baseline gap-x-2">+ <dt className="text-[var(--muted-foreground)]">+ {t("settings.presets.parser")}+ </dt>+ <dd className="min-w-0 font-mono text-[var(--foreground)]">+ {preset.parser}+ </dd>+ </div>+ <div className="flex flex-wrap items-baseline gap-x-2">+ <dt className="text-[var(--muted-foreground)]">+ {t("settings.presets.prerequisites")}+ </dt>+ <dd className="min-w-0 text-[var(--foreground)]">+ {preset.prerequisites+ .map((item) =>+ t(`settings.presets.prerequisite.${item}`),+ )+ .join(" · ")}+ </dd>+ </div>+ <div className="flex flex-wrap items-baseline gap-x-2">+ <dt className="text-[var(--muted-foreground)]">+ {t("settings.presets.credentials")}+ </dt>+ <dd className="min-w-0 text-[var(--foreground)]">+ {preset.credentials+ .map((item) => t(`settings.presets.credential.${item}`))+ .join(" · ")}+ </dd>+ </div>+ <div className="flex flex-wrap items-baseline gap-x-2">+ <dt className="text-[var(--muted-foreground)]">+ {t("settings.presets.features")}+ </dt>+ <dd className="min-w-0 text-[var(--foreground)]">+ {preset.unlocked_features+ .map((item) => t(`settings.presets.feature.${item}`))+ .join(" · ")}+ </dd>+ </div>+ </dl>++ <button+ type="button"+ onClick={() => void load(preset)}+ disabled={saving || !enabled}+ className="mt-4 inline-flex w-fit items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-50"+ >+ {activeId === preset.id && (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ )}+ {t("settings.presets.loadDraft")}+ </button>+ </article>+ ))}+ </div>+ )}+ </section>+ );+}diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.tsindex c950b5168..c1d0c1388 100644--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@ -7039,6 +7039,46 @@ export interface paths {readonly patch?: never;readonly trace?: never;};+ readonly "/api/settings/presets": {+ readonly parameters: {+ readonly query?: never;+ readonly header?: never;+ readonly path?: never;+ readonly cookie?: never;+ };+ /**+ * Get Settings Presets+ * @description List value-free starting points for a reviewable draft.+ */+ readonly get: operations["get_settings_presets_api_settings_presets_get"];+ readonly put?: never;+ readonly post?: never;+ readonly delete?: never;+ readonly options?: never;+ readonly head?: never;+ readonly patch?: never;+ readonly trace?: never;+ };+ readonly "/api/settings/presets/{preset_id}/draft": {+ readonly parameters: {+ readonly query?: never;+ readonly header?: never;+ readonly path?: never;+ readonly cookie?: never;+ };+ readonly get?: never;+ readonly put?: never;+ /**+ * Stage Settings Preset+ * @description Load a named preset into the existing draft for review.+ */+ readonly post: operations["stage_settings_preset_api_settings_presets__preset_id__draft_post"];+ readonly delete?: never;+ readonly options?: never;+ readonly head?: never;+ readonly patch?: never;+ readonly trace?: never;+ };readonly "/api/settings/providers/codebuddy/auth/cancel": {readonly parameters: {readonly query?: never;@@ -12352,6 +12392,20 @@ export interface components {readonly [key: string]: unknown;};};+ /**+ * SettingsPresetDraftRequest+ * @description The current draft envelope submitted alongside a named preset.+ */+ readonly SettingsPresetDraftRequest: {+ /** Catalog */+ readonly catalog?: {+ readonly [key: string]: unknown;+ } | null;+ /** Extensions */+ readonly extensions?: {+ readonly [key: string]: unknown;+ };+ };/** SidebarDescriptionUpdate */readonly SidebarDescriptionUpdate: {/** Description */@@ -13898,6 +13952,8 @@ export type SchemaSetSyllabusRequest =components["schemas"]["SetSyllabusRequest"];export type SchemaSettingsDraftPayload =components["schemas"]["SettingsDraftPayload"];+export type SchemaSettingsPresetDraftRequest =+ components["schemas"]["SettingsPresetDraftRequest"];export type SchemaSidebarDescriptionUpdate =components["schemas"]["SidebarDescriptionUpdate"];export type SchemaSidebarNavOrder = components["schemas"]["SidebarNavOrder"];@@ -29978,6 +30034,80 @@ export interface operations {};};};+ readonly get_settings_presets_api_settings_presets_get: {+ readonly parameters: {+ readonly query?: never;+ readonly header?: {+ readonly Authorization?: string | null;+ };+ readonly path?: never;+ readonly cookie?: {+ readonly dt_token?: string | null;+ };+ };+ readonly requestBody?: never;+ readonly responses: {+ /** @description Successful Response */+ readonly 200: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": unknown;+ };+ };+ /** @description Validation Error */+ readonly 422: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ readonly stage_settings_preset_api_settings_presets__preset_id__draft_post: {+ readonly parameters: {+ readonly query?: never;+ readonly header?: {+ readonly Authorization?: string | null;+ };+ readonly path: {+ readonly preset_id: string;+ };+ readonly cookie?: {+ readonly dt_token?: string | null;+ };+ };+ readonly requestBody: {+ readonly content: {+ readonly "application/json": components["schemas"]["SettingsPresetDraftRequest"];+ };+ };+ readonly responses: {+ /** @description Successful Response */+ readonly 200: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": {+ readonly [key: string]: unknown;+ };+ };+ };+ /** @description Validation Error */+ readonly 422: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };readonly cancel_codebuddy_auth_api_settings_providers_codebuddy_auth_cancel_post: {readonly parameters: {readonly query?: never;diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.jsonindex 8685a2efe..c290cc2b5 100644--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@ -7165,6 +7165,30 @@"title": "SettingsDraftPayload","type": "object"},+ "SettingsPresetDraftRequest": {+ "description": "The current draft envelope submitted alongside a named preset.",+ "properties": {+ "catalog": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Catalog"+ },+ "extensions": {+ "additionalProperties": true,+ "title": "Extensions",+ "type": "object"+ }+ },+ "title": "SettingsPresetDraftRequest",+ "type": "object"+ },"SidebarDescriptionUpdate": {"properties": {"description": {@@ -43361,6 +43385,157 @@]}},+ "/api/settings/presets": {+ "get": {+ "description": "List value-free starting points for a reviewable draft.",+ "operationId": "get_settings_presets_api_settings_presets_get",+ "parameters": [+ {+ "in": "header",+ "name": "Authorization",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Authorization"+ }+ },+ {+ "in": "cookie",+ "name": "dt_token",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Dt Token"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {}+ }+ },+ "description": "Successful Response"+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ },+ "description": "Validation Error"+ }+ },+ "summary": "Get Settings Presets",+ "tags": [+ "settings"+ ]+ }+ },+ "/api/settings/presets/{preset_id}/draft": {+ "post": {+ "description": "Load a named preset into the existing draft for review.",+ "operationId": "stage_settings_preset_api_settings_presets__preset_id__draft_post",+ "parameters": [+ {+ "in": "path",+ "name": "preset_id",+ "required": true,+ "schema": {+ "title": "Preset Id",+ "type": "string"+ }+ },+ {+ "in": "header",+ "name": "Authorization",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Authorization"+ }+ },+ {+ "in": "cookie",+ "name": "dt_token",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Dt Token"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SettingsPresetDraftRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "additionalProperties": true,+ "title": "Response Stage Settings Preset Api Settings Presets Preset Id Draft Post",+ "type": "object"+ }+ }+ },+ "description": "Successful Response"+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ },+ "description": "Validation Error"+ }+ },+ "summary": "Stage Settings Preset",+ "tags": [+ "settings"+ ]+ }+ },"/api/settings/providers/codebuddy/auth/cancel": {"post": {"operationId": "cancel_codebuddy_auth_api_settings_providers_codebuddy_auth_cancel_post",@@ -49642,7 +49817,9 @@}},"summary": "Browse Invidious",- "tags": ["video-learning"]+ "tags": [+ "video-learning"+ ]}},"/api/video-learning/materials/resolve": {diff --git a/web/features/settings/store/SettingsStore.tsx b/web/features/settings/store/SettingsStore.tsxindex f98044614..e049badbe 100644--- a/web/features/settings/store/SettingsStore.tsx+++ b/web/features/settings/store/SettingsStore.tsx@@ -661,6 +661,8 @@ export type SettingsContextValue = {/** Promote one model service without applying unrelated Settings drafts. */applyService: (service: ServiceName) => Promise<boolean>;discardDraft: () => Promise<void>;+ /** Stage a named Settings preset as a reviewable draft. */+ stagePreset: (presetId: string) => Promise<boolean>;/** A draft parked on the server, waiting to be applied. */storedDraft: StoredDraft | null;draftState: DraftState;@@ -1695,6 +1697,60 @@ export function SettingsProvider({ children }: { children: ReactNode }) {}}, [catalogEditable, clearPending, draftEnvelope, t]);+ /** Stage a named preset over the current draft without applying anything. */+ const stagePreset = useCallback(+ async (presetId: string): Promise<boolean> => {+ setSaving(true);+ try {+ const response = await apiFetch(+ apiUrl(`/api/settings/presets/${presetId}/draft`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(draftEnvelope()),+ },+ );+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ const payload = (await response.json()) as {+ draft: StoredDraft | null;+ };+ const stored = payload.draft;+ const pending = new Map(+ Object.entries(stored?.extensions ?? {}),+ );++ pendingRef.current.clear();+ for (const [key, value] of pending.entries()) {+ pendingRef.current.set(key, value);+ }+ syncPendingKeys();+ if (stored?.catalog) setDraft(cloneCatalog(stored.catalog));+ setStoredDraft(stored);+ // The server has the exact staged envelope; avoid the toolbar calling+ // it unsaved while the new draft signature is still propagating.+ setSavedSignature(+ JSON.stringify({+ catalog: catalogEditable ? (stored?.catalog ?? draft) : null,+ extensions: JSON.stringify(Object.fromEntries(pending.entries())),+ }),+ );+ setDraftRevision((value) => value + 1);+ setToast(t("Preset loaded as a draft — review before applying"));+ return true;+ } catch (err) {+ setToast(+ t("Could not load the preset: {{message}}", {+ message: err instanceof Error ? err.message : String(err),+ }),+ );+ return false;+ } finally {+ setSaving(false);+ }+ },+ [catalogEditable, draft, draftEnvelope, syncPendingKeys, t],+ );+/** Throw the draft away and go back to what is actually live. */const discardDraft = useCallback(async () => {setApplying(true);@@ -2022,6 +2078,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {applyCatalog,applyService,discardDraft,+ stagePreset,storedDraft,draftState,draftRevision,@@ -2049,6 +2106,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {applyCatalog,applyService,applying,+ stagePreset,draftState,storedDraft,draftRevision,diff --git a/web/lib/settings-extensions.ts b/web/lib/settings-extensions.tsindex 65202fee3..bd07f29a7 100644--- a/web/lib/settings-extensions.ts+++ b/web/lib/settings-extensions.ts@@ -20,6 +20,8 @@ export const EXTENSION_ENDPOINTS = {capabilities: "/api/capabilities/settings",memory: "/api/memory/settings",network: "/api/settings/network",+ "document_parsing": "/api/settings/document-parsing",+ enabled_tools: "/api/settings/enabled-tools",} as const;export type ExtensionKey = keyof typeof EXTENSION_ENDPOINTS;diff --git a/web/lib/settings-presets.ts b/web/lib/settings-presets.tsnew file mode 100644index 000000000..978d34d7f--- /dev/null+++ b/web/lib/settings-presets.ts@@ -0,0 +1,25 @@+import { apiFetch, apiUrl } from "@/lib/api";++export interface SettingsPreset {+ id: string;+ label: string;+ description: string;+ parser: string;+ resource_cost: "low" | "medium" | "high";+ credentials: string[];+ prerequisites: string[];+ unlocked_features: string[];+}++export interface SettingsPresetsPayload {+ schema_version: "deeptutor.settings-presets/v1";+ presets: SettingsPreset[];+}++export async function fetchSettingsPresets(): Promise<SettingsPresetsPayload> {+ const response = await apiFetch(apiUrl("/api/settings/presets"));+ if (!response.ok) {+ throw new Error(`Settings presets failed: HTTP ${response.status}`);+ }+ return (await response.json()) as SettingsPresetsPayload;+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex ea72027d8..7af8cd848 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -4045,5 +4045,41 @@"The Invidious instance could not verify your account. Check the instance and reconnect.": "The Invidious instance could not verify your account. Check the instance and reconnect.","Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.": "Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.","The account could not be connected. Please start a new connection.": "The account could not be connected. Please start a new connection.",- "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate."+ "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.",+ "settings.presets.title": "Starting points",+ "settings.presets.blurb": "Load a reviewed preset as a draft. Nothing changes until you apply it.",+ "settings.presets.error": "Presets could not be loaded.",+ "settings.presets.empty": "No presets are available.",+ "settings.presets.loadDraft": "Load draft",+ "settings.presets.parser": "Parser",+ "settings.presets.prerequisites": "Needs",+ "settings.presets.credentials": "Credentials",+ "settings.presets.features": "Unlocks",+ "settings.presets.cost.low": "Low cost",+ "settings.presets.cost.medium": "Medium cost",+ "settings.presets.cost.high": "High cost",+ "settings.presets.basic_text.name": "Basic text",+ "settings.presets.basic_text.description": "A quiet text-first setup for chat, notes, and focused reasoning.",+ "settings.presets.local_multimodal.name": "Local multimodal",+ "settings.presets.local_multimodal.description": "Parse documents locally and prepare image and video generation tools.",+ "settings.presets.university_study.name": "University study",+ "settings.presets.university_study.description": "Combine document parsing with web and paper search for research work.",+ "settings.presets.full_generation.name": "Full generation",+ "settings.presets.full_generation.description": "Turn on the complete generation toolkit when every provider is configured.",+ "settings.presets.credential.llm": "Language model",+ "settings.presets.credential.imagegen": "Image model",+ "settings.presets.credential.videogen": "Video model",+ "settings.presets.prerequisite.llm_profile": "model profile",+ "settings.presets.prerequisite.markdown_parser": "markdown parser",+ "settings.presets.prerequisite.media_profiles": "media profiles",+ "settings.presets.prerequisite.search_profile": "search profile",+ "settings.presets.feature.core_chat": "core chat",+ "settings.presets.feature.reasoning": "reasoning",+ "settings.presets.feature.document_parsing": "document parsing",+ "settings.presets.feature.web_search": "web search",+ "settings.presets.feature.paper_search": "paper search",+ "settings.presets.feature.image_generation": "image generation",+ "settings.presets.feature.video_generation": "video generation",+ "Preset loaded as a draft — review before applying": "Preset loaded as a draft — review before applying",+ "Could not load the preset: {{message}}": "Could not load the preset: {{message}}"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 702df3f39..9a49bf6f7 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -4045,5 +4045,41 @@"The Invidious instance could not verify your account. Check the instance and reconnect.": "Invidious 实例暂时无法验证账号,请检查实例后重新关联。","Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.": "授权期间 DeepTutor 登录已失效,请先登录 DeepTutor,再重新关联 Invidious。","The account could not be connected. Please start a new connection.": "账号关联失败,请重新发起关联。",- "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "请使用 Invidious 账号登录,确认只读授权后会自动返回此页。DeepTutor 与 Invidious 使用各自的登录账号。"+ "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "请使用 Invidious 账号登录,确认只读授权后会自动返回此页。DeepTutor 与 Invidious 使用各自的登录账号。",+ "settings.presets.title": "配置起点",+ "settings.presets.blurb": "将预设加载为草稿;只有应用后才会更改设置。",+ "settings.presets.error": "无法加载配置预设。",+ "settings.presets.empty": "当前没有可用预设。",+ "settings.presets.loadDraft": "加载草稿",+ "settings.presets.parser": "解析引擎",+ "settings.presets.prerequisites": "前置条件",+ "settings.presets.credentials": "所需凭据",+ "settings.presets.features": "解锁能力",+ "settings.presets.cost.low": "低成本",+ "settings.presets.cost.medium": "中等成本",+ "settings.presets.cost.high": "高成本",+ "settings.presets.basic_text.name": "基础文本",+ "settings.presets.basic_text.description": "面向聊天、笔记和专注推理的轻量文本配置。",+ "settings.presets.local_multimodal.name": "本地多模态",+ "settings.presets.local_multimodal.description": "本地解析文档,并准备图像与视频生成工具。",+ "settings.presets.university_study.name": "大学学习",+ "settings.presets.university_study.description": "结合文档解析、网页搜索和论文检索,支持研究型学习。",+ "settings.presets.full_generation.name": "完整生成",+ "settings.presets.full_generation.description": "在所有服务配置完成后启用完整生成工具。",+ "settings.presets.credential.llm": "语言模型",+ "settings.presets.credential.imagegen": "图像模型",+ "settings.presets.credential.videogen": "视频模型",+ "settings.presets.prerequisite.llm_profile": "模型配置",+ "settings.presets.prerequisite.markdown_parser": "Markdown 解析器",+ "settings.presets.prerequisite.media_profiles": "媒体服务配置",+ "settings.presets.prerequisite.search_profile": "搜索服务配置",+ "settings.presets.feature.core_chat": "核心聊天",+ "settings.presets.feature.reasoning": "深度推理",+ "settings.presets.feature.document_parsing": "文档解析",+ "settings.presets.feature.web_search": "网页搜索",+ "settings.presets.feature.paper_search": "论文检索",+ "settings.presets.feature.image_generation": "图像生成",+ "settings.presets.feature.video_generation": "视频生成",+ "Preset loaded as a draft — review before applying": "预设已加载为草稿——请检查后再应用",+ "Could not load the preset: {{message}}": "无法加载预设:{{message}}"}diff --git a/web/tests/settings-presets.test.ts b/web/tests/settings-presets.test.tsnew file mode 100644index 000000000..a6212f3a6--- /dev/null+++ b/web/tests/settings-presets.test.ts@@ -0,0 +1,79 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";+import test from "node:test";++const WEB = process.cwd();++function source(file: string): string {+ return readFileSync(path.join(WEB, file), "utf8");+}++function locale(name: string): Record<string, string> {+ return JSON.parse(+ readFileSync(path.join(WEB, "locales", name, "app.json"), "utf8"),+ ) as Record<string, string>;+}++test("preset drafts reuse the apply flow that owns each setting", () => {+ const endpoints = source("lib/settings-extensions.ts");+ assert.match(endpoints, /"document_parsing": "\/api\/settings\/document-parsing"/);+ assert.match(endpoints, /enabled_tools: "\/api\/settings\/enabled-tools"/);++ const panel = source("components/settings/SettingsPresetsPanel.tsx");+ assert.match(panel, /stagePreset\(preset\.id\)/);+ assert.doesNotMatch(panel, /apiFetch|applyCatalog/);+});++test("staging happens against the draft endpoint, not the apply endpoint", () => {+ const store = source("features/settings/store/SettingsStore.tsx");+ const staged = store.slice(+ store.indexOf("const stagePreset = useCallback("),+ store.indexOf("/** Throw the draft away"),+ );++ assert.match(staged, /\/api\/settings\/presets\/\$\{presetId\}\/draft/);+ assert.match(staged, /method: "POST"/);+ assert.doesNotMatch(staged, /\/api\/settings\/apply/);+});++test("preset copy exists in both locales, including composed keys", () => {+ const en = locale("en");+ const zh = locale("zh");+ const keys = [+ "settings.presets.title",+ "settings.presets.blurb",+ "settings.presets.error",+ "settings.presets.empty",+ "settings.presets.loadDraft",+ "settings.presets.parser",+ "settings.presets.basic_text.name",+ "settings.presets.basic_text.description",+ "settings.presets.local_multimodal.name",+ "settings.presets.local_multimodal.description",+ "settings.presets.university_study.name",+ "settings.presets.university_study.description",+ "settings.presets.full_generation.name",+ "settings.presets.full_generation.description",+ "settings.presets.cost.low",+ "settings.presets.cost.medium",+ "settings.presets.cost.high",+ "settings.presets.credential.llm",+ "settings.presets.credential.imagegen",+ "settings.presets.credential.videogen",+ "settings.presets.prerequisite.llm_profile",+ "settings.presets.prerequisite.markdown_parser",+ "settings.presets.prerequisite.media_profiles",+ "settings.presets.prerequisite.search_profile",+ "settings.presets.feature.core_chat",+ "settings.presets.feature.reasoning",+ "settings.presets.feature.document_parsing",+ "settings.presets.feature.web_search",+ "settings.presets.feature.paper_search",+ "settings.presets.feature.image_generation",+ "settings.presets.feature.video_generation",+ ];++ const missing = keys.filter((key) => !(key in en) || !(key in zh));+ assert.deepEqual(missing, []);+});