DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(web): split settings into feature-owned sections
Bingxi Zhao (Frank)3802991e79e6
diff --git a/web/app/(utility)/settings/about/page.tsx b/web/app/(utility)/settings/about/page.tsxindex d67d9d680..8612b16d5 100644--- a/web/app/(utility)/settings/about/page.tsx+++ b/web/app/(utility)/settings/about/page.tsx@@ -1,480 +1 @@-"use client";--import { useCallback, useEffect, useMemo, useState } from "react";-import {- ArrowUpRight,- Check,- CircleAlert,- Download,- Github,- RefreshCw,- RotateCw,- ShieldCheck,-} from "lucide-react";-import { useTranslation } from "react-i18next";--import { Toggle } from "@/components/settings/Toggle";-import {- SettingRow,- SettingSection,- SettingsPageHeader,-} from "@/components/settings/shared";-import { ConfirmDialog } from "@/components/ui/ConfirmDialog";-import Button from "@/components/ui/Button";-import {- checkAppUpdate,- fetchAppUpdateJob,- fetchAppUpdateStatus,- requestAppUpdate,- setAppUpdateChecks,- updateJobIsActive,- type AppUpdateStatus,- type InstallMode,- type UpdateJob,- type UpdateJobStatus,-} from "@/lib/app-update";-import { normalizeVersionTag } from "@/lib/version";--const POLL_INTERVAL_MS = 800;-const POLL_TIMEOUT_MS = 120_000;--const INSTALLATION_LABELS: Record<InstallMode, string> = {- pypi: "PyPI package",- source: "Source checkout",- docker: "Docker container",- unknown: "Unknown installation",-};--function jobTone(status: UpdateJobStatus) {- if (status === "failed") return "text-red-600 dark:text-red-400";- if (status === "succeeded") return "text-emerald-700 dark:text-emerald-400";- return "text-sky-700 dark:text-sky-400";-}--export default function AboutSettingsPage() {- const { t, i18n } = useTranslation();- const [status, setStatus] = useState<AppUpdateStatus | null>(null);- const [job, setJob] = useState<UpdateJob | null>(null);- const [loading, setLoading] = useState(true);- const [checking, setChecking] = useState(false);- const [savingChecks, setSavingChecks] = useState(false);- const [requesting, setRequesting] = useState(false);- const [confirmOpen, setConfirmOpen] = useState(false);- const [error, setError] = useState("");-- const load = useCallback(async () => {- try {- const next = await fetchAppUpdateStatus();- setStatus(next);- setJob(next.job);- setError(next.check_error || "");- } catch (cause) {- setError(- cause instanceof Error- ? cause.message- : (t("Unable to load version information.") as string),- );- } finally {- setLoading(false);- }- }, [t]);-- useEffect(() => {- void load();- }, [load]);-- const activeJob = Boolean(job && updateJobIsActive(job.status));- useEffect(() => {- if (!activeJob) return;- let cancelled = false;- let timer: ReturnType<typeof setTimeout> | undefined;- const deadline = Date.now() + POLL_TIMEOUT_MS;-- const poll = async () => {- try {- const next = await fetchAppUpdateJob();- if (cancelled) return;- if (next) {- setJob(next);- if (!updateJobIsActive(next.status)) {- if (next.status === "succeeded") await load();- return;- }- }- } catch {- // The backend is expected to disappear while the launcher updates and- // restarts it. Keep polling until it reconnects or the deadline passes.- }- if (cancelled) return;- if (Date.now() >= deadline) {- setError(t("DeepTutor did not reconnect before the update timeout."));- return;- }- timer = setTimeout(poll, POLL_INTERVAL_MS);- };-- void poll();- return () => {- cancelled = true;- if (timer) clearTimeout(timer);- };- }, [activeJob, load, t]);-- const check = useCallback(async () => {- setChecking(true);- setError("");- try {- const next = await checkAppUpdate();- setStatus(next);- setJob(next.job);- } catch (cause) {- setError(- cause instanceof Error- ? cause.message- : (t("Unable to check for updates.") as string),- );- } finally {- setChecking(false);- }- }, [t]);-- const changeChecks = useCallback(- async (enabled: boolean) => {- setSavingChecks(true);- setError("");- try {- const next = await setAppUpdateChecks(enabled);- setStatus(next);- setJob(next.job);- } catch (cause) {- setError(- cause instanceof Error- ? cause.message- : (t("Unable to save update settings.") as string),- );- } finally {- setSavingChecks(false);- }- },- [t],- );-- const update = useCallback(async () => {- setRequesting(true);- setError("");- try {- const next = await requestAppUpdate();- setJob(next);- setConfirmOpen(false);- } catch (cause) {- setError(- cause instanceof Error- ? cause.message- : (t("Unable to start the update.") as string),- );- } finally {- setRequesting(false);- }- }, [t]);-- const currentVersion =- normalizeVersionTag(status?.current_version) ??- normalizeVersionTag(process.env.NEXT_PUBLIC_APP_VERSION) ??- "—";- const latestVersion = normalizeVersionTag(status?.release?.version);- const checkedAt = useMemo(() => {- if (!status?.checked_at) return "";- const parsed = new Date(status.checked_at);- if (Number.isNaN(parsed.getTime())) return "";- return parsed.toLocaleString(- i18n.language?.toLowerCase().startsWith("zh") ? "zh-CN" : "en-US",- { dateStyle: "medium", timeStyle: "short" },- );- }, [i18n.language, status?.checked_at]);-- const installMode = status?.installation.mode ?? "unknown";- const canUpdate = Boolean(- status?.is_admin &&- status.check_enabled &&- status.update_available &&- status.installation.automatic_update &&- status.launcher_managed &&- !activeJob,- );- const upToDate = Boolean(status?.release && !status.update_available);-- return (- <div data-tour="tour-about" className="pb-8">- <SettingsPageHeader- title={t("About")}- description={t(- "DeepTutor version, release channel, and the safest update path for this installation.",- )}- />-- <section className="relative mb-10 overflow-hidden border-y border-[var(--border)]/60 py-7">- <div- aria-hidden- className="pointer-events-none absolute -right-12 -top-16 h-40 w-40 rounded-full border-[28px] border-[var(--foreground)]/[0.025]"- />- <div className="relative flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">- <div>- <div className="mb-2 flex items-center gap-2 text-[11px] font-medium uppercase tracking-[0.16em] text-[var(--muted-foreground)]">- <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />- {t("Running version")}- </div>- <div className="font-serif text-[38px] font-semibold leading-none tracking-[-0.035em] text-[var(--foreground)]">- {currentVersion}- </div>- </div>- <div className="flex flex-wrap items-center gap-2">- {status?.release?.url && (- <a- href={status.release.url}- target="_blank"- rel="noreferrer noopener"- className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--accent)] hover:text-[var(--foreground)]"- >- {t("Release notes")}- <ArrowUpRight className="h-3.5 w-3.5" />- </a>- )}- {status?.is_admin && (- <Button- type="button"- size="sm"- variant="secondary"- loading={checking}- disabled={!status.check_enabled || activeJob}- icon={<RefreshCw className="h-3.5 w-3.5" />}- onClick={() => void check()}- >- {t("Check now")}- </Button>- )}- {canUpdate && (- <Button- type="button"- size="sm"- icon={<Download className="h-3.5 w-3.5" />}- onClick={() => setConfirmOpen(true)}- >- {t("Update to {{version}}", { version: latestVersion ?? "" })}- </Button>- )}- </div>- </div>- </section>-- {error && (- <div className="mb-7 flex items-start gap-2 border-l-2 border-red-500/70 py-1 pl-3 text-[12.5px] leading-relaxed text-red-600 dark:text-red-400">- <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />- <span>{error}</span>- </div>- )}-- <SettingSection title={t("Software")}>- <SettingRow- title={t("Current version")}- control={<CodeValue value={currentVersion} />}- />- <SettingRow- title={t("Installation")}- description={t(- status?.installation.reason || "How DeepTutor is installed here.",- )}- control={- <span className="text-[12.5px] text-[var(--foreground)]">- {t(INSTALLATION_LABELS[installMode])}- </span>- }- />- <SettingRow- title={t("Release channel")}- description={t(- "Only stable, published DeepTutor releases are considered.",- )}- control={- <span className="text-[12.5px] text-[var(--foreground)]">- {t("Stable")}- </span>- }- />- </SettingSection>-- <SettingSection- title={t("Updates")}- description={t(- "Version checks are cached for 24 hours. DeepTutor never installs an update without confirmation.",- )}- >- <SettingRow- title={t("Check for updates")}- description={t(- "Turn this off for offline or controlled deployments.",- )}- control={- status?.is_admin ? (- <Toggle- checked={status?.check_enabled ?? true}- disabled={loading || savingChecks || activeJob}- onChange={(enabled) => void changeChecks(enabled)}- />- ) : (- <span className="text-[12.5px] text-[var(--muted-foreground)]">- {status?.check_enabled ? t("On") : t("Off")}- </span>- )- }- />- <SettingRow- title={t("Latest stable release")}- description={- checkedAt- ? t("Last checked {{time}}", { time: checkedAt })- : status?.check_enabled- ? t("Not checked yet")- : t("Version checks are disabled.")- }- control={- <div className="flex items-center gap-2">- {upToDate && <Check className="h-3.5 w-3.5 text-emerald-500" />}- <CodeValue value={latestVersion ?? "—"} />- </div>- }- />-- {status?.release?.migration_warning && (- <div className="flex items-start gap-2 border-t border-[var(--border)]/50 py-3.5 text-[12.5px] leading-relaxed text-amber-700 dark:text-amber-400">- <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />- {t(- "This release mentions migrations or breaking changes. Read the release notes before updating.",- )}- </div>- )}-- {status?.release?.excerpt && (- <div className="border-t border-[var(--border)]/50 py-4">- <div className="mb-2 text-[11px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">- {status.release.name || t("What changed")}- </div>- <p className="max-w-2xl whitespace-pre-line text-[12.5px] leading-6 text-[var(--muted-foreground)]">- {status.release.excerpt}- </p>- </div>- )}-- {status && !status.installation.automatic_update && (- <div className="border-t border-[var(--border)]/50 py-4">- <div className="mb-2 flex items-center gap-2 text-[12.5px] font-medium text-[var(--foreground)]">- <ShieldCheck className="h-4 w-4 text-[var(--muted-foreground)]" />- {t("Managed by your installation")}- </div>- <p className="mb-3 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">- {t(status.installation.reason)}- </p>- <code className="block overflow-x-auto rounded-lg bg-[var(--accent)]/60 px-3 py-2 text-[11.5px] text-[var(--foreground)]">- {status.installation.command}- </code>- </div>- )}-- {job && (- <div- className="border-t border-[var(--border)]/50 py-4"- aria-live="polite"- >- <div- className={`flex items-center gap-2 text-[12.5px] font-medium ${jobTone(job.status)}`}- >- {updateJobIsActive(job.status) ? (- <RotateCw className="h-3.5 w-3.5 animate-spin" />- ) : job.status === "succeeded" ? (- <Check className="h-3.5 w-3.5" />- ) : (- <CircleAlert className="h-3.5 w-3.5" />- )}- {t(`updateJob.${job.status}`)}- </div>- {job.error && (- <p className="mt-2 text-[12px] text-red-600 dark:text-red-400">- {job.error}- </p>- )}- </div>- )}- </SettingSection>-- <SettingSection title={t("Project")}>- <ResourceRow- title={t("GitHub")}- description={t("Source code, issues, and contributions")}- href="https://github.com/HKUDS/DeepTutor"- icon={<Github className="h-4 w-4" />}- />- <ResourceRow- title={t("Documentation")}- description={t("Installation, configuration, and guides")}- href="https://docs.deeptutor.info"- icon={<ArrowUpRight className="h-4 w-4" />}- />- </SettingSection>-- <ConfirmDialog- open={confirmOpen}- title={t("Update and restart DeepTutor?")}- confirmLabel={t("Update and restart")}- busy={requesting}- busyLabel={t("Preparing update…")}- onConfirm={() => void update()}- onCancel={() => setConfirmOpen(false)}- >- {t(- "DeepTutor will briefly stop, install {{version}}, and reopen with the same settings. Active conversations must finish first.",- { version: latestVersion ?? "" },- )}- </ConfirmDialog>- </div>- );-}--function CodeValue({ value }: { value: string }) {- return (- <code className="rounded-md bg-[var(--accent)]/60 px-2 py-1 text-[11.5px] tabular-nums text-[var(--foreground)]">- {value}- </code>- );-}--function ResourceRow({- title,- description,- href,- icon,-}: {- title: string;- description: string;- href: string;- icon: React.ReactNode;-}) {- return (- <a- href={href}- target="_blank"- rel="noreferrer noopener"- className="group flex items-center justify-between gap-5 border-t border-[var(--border)]/50 py-3.5 first:border-t-0"- >- <div>- <div className="text-[13.5px] font-medium text-[var(--foreground)]">- {title}- </div>- <p className="mt-1 text-[12px] text-[var(--muted-foreground)]">- {description}- </p>- </div>- <span className="text-[var(--muted-foreground)] transition-transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5 group-hover:text-[var(--foreground)]">- {icon}- </span>- </a>- );-}+export { default } from "@/features/settings/sections/AboutSettingsSection";diff --git a/web/app/(utility)/settings/agents/page.tsx b/web/app/(utility)/settings/agents/page.tsxindex 90d836fe4..a57f5b4ac 100644--- a/web/app/(utility)/settings/agents/page.tsx+++ b/web/app/(utility)/settings/agents/page.tsx@@ -1,39 +1 @@-"use client";--import { CategoryScroll } from "@/components/settings/CategoryScroll";--import ClaudeCodeAgentSettingsPage from "./claude-code/page";-import CodexAgentSettingsPage from "./codex/page";-import AntigravityAgentSettingsPage from "./antigravity/page";-import KimiAgentSettingsPage from "./kimi/page";-import OpencodeAgentSettingsPage from "./opencode/page";-import MimoAgentSettingsPage from "./mimo/page";-import HermesAgentSettingsPage from "./hermes/page";-import OpenClawAgentSettingsPage from "./openclaw/page";-import DeepSeekHarnessAgentSettingsPage from "./deepseek-harness/page";--/**- * The Partners & Agents category, in full — see `ModelsSettingsPage` for the- * pattern. All leaves persist to the same `subagent.json`, so this remains one- * shared draft behind the individual routes.- */-export default function AgentsSettingsPage() {- return (- <CategoryScroll- sections={[- { key: "agent-claude-code", Component: ClaudeCodeAgentSettingsPage },- { key: "agent-codex", Component: CodexAgentSettingsPage },- { key: "agent-antigravity", Component: AntigravityAgentSettingsPage },- { key: "agent-kimi", Component: KimiAgentSettingsPage },- { key: "agent-opencode", Component: OpencodeAgentSettingsPage },- { key: "agent-mimo", Component: MimoAgentSettingsPage },- { key: "agent-hermes", Component: HermesAgentSettingsPage },- { key: "agent-openclaw", Component: OpenClawAgentSettingsPage },- {- key: "agent-deepseek-harness",- Component: DeepSeekHarnessAgentSettingsPage,- },- ]}- />- );-}+export { default } from "@/features/settings/sections/AgentsSettingsSection";diff --git a/web/app/(utility)/settings/appearance/page.tsx b/web/app/(utility)/settings/appearance/page.tsxindex 1578b88ff..30345a4e7 100644--- a/web/app/(utility)/settings/appearance/page.tsx+++ b/web/app/(utility)/settings/appearance/page.tsx@@ -1,241 +1 @@-"use client";--import dynamic from "next/dynamic";-import { useTranslation } from "react-i18next";--import type { CodeBlockThemeId } from "@/components/common/code-block-themes";-import { CODE_BLOCK_THEME_OPTIONS } from "@/components/common/code-block-themes";-import { Toggle } from "@/components/settings/Toggle";-import { useSettings } from "@/components/settings/SettingsContext";-import { ThemePreviewCard } from "@/components/settings/ThemePreviewCard";-import {- SettingRow,- SettingSection,- SettingsPageHeader,- selectClass,- selectOptionClass,-} from "@/components/settings/shared";--const CODE_BLOCK_PREVIEW_SNIPPET = `def fibonacci(n):- """Generate the first n Fibonacci numbers."""- a, b = 0, 1- result = []- for _ in range(n):- result.append(a)- a, b = b, a + b- return result---# Build a deliberately long summary so the wrapping preference is easy to see-summary = f"First twenty Fibonacci values rendered with the selected syntax theme, line-number setting, and wrapping preference: {', '.join(str(value) for value in fibonacci(20))}"-print(summary)-`;--const RichCodeBlockPreview = dynamic(- () => import("@/components/common/RichCodeBlock"),- { ssr: false },-);--export default function AppearanceSettingsPage() {- const { t } = useTranslation();- const {- theme,- language,- responseLanguage,- codeBlockTheme,- codeBlockShowLineNumbers,- codeBlockWrapLongLines,- updateTheme,- updateLanguage,- updateResponseLanguage,- updateCodeBlockTheme,- updateCodeBlockShowLineNumbers,- updateCodeBlockWrapLongLines,- } = useSettings();-- // All code-block values come straight from the settings context (backed by- // AppShellContext, the single source of truth), so the toggles reflect the- // current preference without any local mirror state.- const handleShowLineNumbersChange = (next: boolean) => {- void updateCodeBlockShowLineNumbers(next);- };-- const handleWrapLongLinesChange = (next: boolean) => {- void updateCodeBlockWrapLongLines(next);- };-- return (- <div data-tour="tour-appearance">- <SettingsPageHeader- title={t("Appearance")}- description={t(- "Tune the visual theme and interface language. Changes apply immediately and are stored in your account.",- )}- />-- <SettingSection- title={t("Language")}- description={t("Choose the interface language.")}- >- <SettingRow- title={t("Interface language")}- description={t(- "Controls navigation, settings, and status text only.",- )}- control={- <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">- {(["en", "zh"] as const).map((v) => (- <button- key={v}- onClick={() => updateLanguage(v)}- className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${- language === v- ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- {v === "en" ? t("language.english") : t("language.chinese")}- </button>- ))}- </div>- }- />- <SettingRow- title={t("Model output language")}- description={t(- "Sets the default language for chat and capability responses.",- )}- control={- <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">- {(["en", "zh"] as const).map((value) => (- <button- key={value}- onClick={() => updateResponseLanguage(value)}- className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${- responseLanguage === value- ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- {value === "en"- ? t("language.english")- : t("language.chinese")}- </button>- ))}- </div>- }- />- </SettingSection>-- <SettingSection- title={t("Theme")}- description={t(- "Pick the colour palette and interface style. Each tile previews the theme it applies.",- )}- >- <div className="py-3.5">- {/* Order is intentional: Default (pure-white neutral, the default- selection; theme id "snow" kept for stored preferences) →- warm-light Cream → warm-dark Dark → cool-dark Glass. */}- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- {(- [- { id: "snow", label: t("Default") },- { id: "light", label: t("Cream") },- { id: "dark", label: t("Dark") },- { id: "glass", label: t("Glass") },- ] as const- ).map(({ id, label }) => (- <ThemePreviewCard- key={id}- theme={id}- label={label}- selected={theme === id}- onSelect={updateTheme}- />- ))}- </div>- <p className="mt-4 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]/80">- {t(- "Default is a clean pure-white theme with a blue accent. Cream is warm and paper-like with a terracotta accent. Dark keeps Cream's warmth on near-black. Glass adds translucent purple panels on a deep gradient.",- )}- </p>- </div>- </SettingSection>-- <SettingSection- title={t("Code blocks")}- description={t(- "Choose how code snippets look across the app. Changes apply immediately to saved and streamed responses.",- )}- >- <div className="border-t border-[var(--border)]/50 py-3.5 first:border-t-0">- <div className="text-[13.5px] font-medium text-[var(--foreground)]">- {t("Preview")}- </div>- <p className="mb-3 mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">- {t("Updates live as you change the settings below.")}- </p>- <RichCodeBlockPreview- raw={CODE_BLOCK_PREVIEW_SNIPPET}- lang="python"- />- </div>-- <SettingRow- title={t("Syntax theme")}- description={t(- "Select the Prism theme used for highlighted code blocks.",- )}- control={- <select- value={codeBlockTheme}- onChange={(event) =>- void updateCodeBlockTheme(- event.target.value as CodeBlockThemeId,- )- }- className={`${selectClass} min-w-[220px] pr-8`}- >- {CODE_BLOCK_THEME_OPTIONS.map((option) => (- <option- key={option.id}- value={option.id}- className={selectOptionClass}- >- {option.label}- </option>- ))}- </select>- }- />-- <SettingRow- title={t("Show line numbers")}- description={t(- "Display a gutter with line numbers beside each code block.",- )}- control={- <Toggle- checked={codeBlockShowLineNumbers}- onChange={handleShowLineNumbersChange}- />- }- />-- <SettingRow- title={t("Wrap long lines")}- description={t(- "Wrap long code lines instead of forcing horizontal scrolling.",- )}- control={- <Toggle- checked={codeBlockWrapLongLines}- onChange={handleWrapLongLinesChange}- />- }- />- </SettingSection>- </div>- );-}+export { default } from "@/features/settings/sections/AppearanceSettingsSection";diff --git a/web/app/(utility)/settings/attachments/page.tsx b/web/app/(utility)/settings/attachments/page.tsxindex edf6ecbf7..8dc39903e 100644--- a/web/app/(utility)/settings/attachments/page.tsx+++ b/web/app/(utility)/settings/attachments/page.tsx@@ -1,274 +1 @@-"use client";--import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Loader2 } from "lucide-react";-import { useTranslation } from "react-i18next";--import {- SettingRow,- SettingSection,- SettingsPageHeader,- inputClass,-} from "@/components/settings/shared";-import { useSettings } from "@/components/settings/SettingsContext";-import { apiFetch, apiUrl } from "@/lib/api";-import { EXTENSION_ENDPOINTS } from "@/lib/settings-extensions";--type AttachmentSettings = {- max_file_mb: number;- max_total_mb: number;- max_chars_per_doc: number;- max_chars_total: number;-};--type AttachmentSettingsPayload = {- settings: AttachmentSettings;- effective: {- max_file_bytes: number;- max_total_bytes: number;- max_chars_per_doc: number;- max_chars_total: number;- ws_max_size: number;- };- bounds: {- max_file_mb: [number, number];- max_total_mb: [number, number];- chars: [number, number];- };- restart_required_for_larger_uploads: boolean;-};--function normalizeDraft(- payload: AttachmentSettingsPayload,-): AttachmentSettings {- return { ...payload.settings };-}--export default function AttachmentSettingsPage() {- const { t } = useTranslation();- const { registerExtension, pendingExtensionPayload, draftRevision } =- useSettings();- const [payload, setPayload] = useState<AttachmentSettingsPayload | null>(- null,- );- const [draft, setDraft] = useState<AttachmentSettings | null>(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- useEffect(() => {- let cancelled = false;- async function load() {- setLoading(true);- setError(null);- try {- const response = await apiFetch(- apiUrl(EXTENSION_ENDPOINTS["chat-attachments"]),- );- const data = (await response.json().catch(() => ({}))) as- | AttachmentSettingsPayload- | { detail?: string };- if (!response.ok) {- throw new Error(- "detail" in data && data.detail- ? data.detail- : t("Failed to load attachment settings."),- );- }- if (cancelled) return;- const next = data as AttachmentSettingsPayload;- setPayload(next);- const pending = pendingExtensionPayload("chat-attachments") as- | AttachmentSettings- | undefined;- setDraft(pending ?? normalizeDraft(next));- } catch (err) {- if (!cancelled) {- setError(err instanceof Error ? err.message : String(err));- }- } finally {- if (!cancelled) setLoading(false);- }- }- load();- return () => {- cancelled = true;- };- }, [draftRevision, pendingExtensionPayload, t]);-- const dirty = useMemo(() => {- if (!payload || !draft) return false;- const current = normalizeDraft(payload);- return (- current.max_file_mb !== draft.max_file_mb ||- current.max_total_mb !== draft.max_total_mb ||- current.max_chars_per_doc !== draft.max_chars_per_doc ||- current.max_chars_total !== draft.max_chars_total- );- }, [draft, payload]);-- // Flush through the global Apply (top toolbar) instead of a local button.- const draftRef = useRef(draft);- draftRef.current = draft;- const save = useCallback(async () => {- const current = draftRef.current;- if (!current) return;- setError(null);- try {- const response = await apiFetch(- apiUrl(EXTENSION_ENDPOINTS["chat-attachments"]),- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(current),- },- );- const data = (await response.json().catch(() => ({}))) as- | AttachmentSettingsPayload- | { detail?: string };- if (!response.ok) {- throw new Error(- "detail" in data && data.detail- ? String(data.detail)- : t("Failed to save attachment settings."),- );- }- const next = data as AttachmentSettingsPayload;- setPayload(next);- setDraft(normalizeDraft(next));- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- }- }, [t]);-- useEffect(() => {- registerExtension("chat-attachments", { dirty, save, payload: draft });- return () => registerExtension("chat-attachments", null);- }, [dirty, draft, save, registerExtension]);-- const setField = (field: keyof AttachmentSettings) => (value: number) =>- setDraft((current) => (current ? { ...current, [field]: value } : current));-- const bounds = payload?.bounds;-- return (- <div>- <SettingsPageHeader- title={t("Attachments")}- description={t(- "Upload caps and extraction budgets for files attached in chat — shared by the main chat, books, quiz follow-ups, and partners.",- )}- />-- {loading && (- <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">- <Loader2 className="h-4 w-4 animate-spin" />- {t("Loading attachment settings...")}- </div>- )}-- {!loading && error && (- <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">- {error}- </div>- )}-- {!loading && payload && draft && (- <>- <SettingSection- title={t("Size limits")}- description={t(- "Caps are enforced when a file is picked and again server-side on every message. Lower limits apply immediately; raising them needs a backend restart so larger uploads fit through the WebSocket transport.",- )}- >- <SettingRow- title={t("Max file size (MB)")}- description={t("Largest single file the composer accepts.")}- control={- <input- className={`${inputClass} w-28`}- type="number"- min={bounds?.max_file_mb[0] ?? 1}- max={bounds?.max_file_mb[1] ?? 1024}- value={draft.max_file_mb}- onChange={(event) =>- setField("max_file_mb")(Number(event.target.value))- }- />- }- />- <SettingRow- title={t("Max total per message (MB)")}- description={t(- "Combined size of all attachments on a single message. Never below the per-file cap.",- )}- control={- <input- className={`${inputClass} w-28`}- type="number"- min={bounds?.max_total_mb[0] ?? 1}- max={bounds?.max_total_mb[1] ?? 2048}- value={draft.max_total_mb}- onChange={(event) =>- setField("max_total_mb")(Number(event.target.value))- }- />- }- />- </SettingSection>-- <SettingSection- title={t("Extraction budgets")}- description={t(- "Documents are converted to text and inlined into the model context. These budgets bound how much text a single file and a whole message may contribute — raise them for large documents, at the cost of context window and tokens.",- )}- >- <SettingRow- title={t("Max characters per document")}- description={t(- "Text extracted beyond this from one file is truncated with a notice.",- )}- control={- <input- className={`${inputClass} w-36`}- type="number"- min={bounds?.chars[0] ?? 10000}- max={bounds?.chars[1] ?? 5000000}- step={10000}- value={draft.max_chars_per_doc}- onChange={(event) =>- setField("max_chars_per_doc")(Number(event.target.value))- }- />- }- />- <SettingRow- title={t("Max characters per message")}- description={t(- "Total extracted text across all documents on one message.",- )}- control={- <input- className={`${inputClass} w-36`}- type="number"- min={bounds?.chars[0] ?? 10000}- max={bounds?.chars[1] ?? 5000000}- step={10000}- value={draft.max_chars_total}- onChange={(event) =>- setField("max_chars_total")(Number(event.target.value))- }- />- }- />- </SettingSection>-- <p className="mt-2 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">- {t(- "Note: images are sent to the model provider as-is — provider-side size limits still apply regardless of these caps.",- )}- </p>- </>- )}- </div>- );-}+export { default } from "@/features/settings/sections/AttachmentsSettingsSection";diff --git a/web/app/(utility)/settings/capabilities/page.tsx b/web/app/(utility)/settings/capabilities/page.tsxindex 9bac1f5c2..332737c5b 100644--- a/web/app/(utility)/settings/capabilities/page.tsx+++ b/web/app/(utility)/settings/capabilities/page.tsx@@ -1,609 +1 @@-"use client";--import { useCallback, useEffect, useRef, useState } from "react";-import { Loader2 } from "lucide-react";-import { useTranslation } from "react-i18next";--import { apiFetch, apiUrl } from "@/lib/api";-import { EXTENSION_ENDPOINTS } from "@/lib/settings-extensions";-import {- SettingRow,- SettingSection,- SettingsPageHeader,-} from "@/components/settings/shared";-import { useSettings } from "@/components/settings/SettingsContext";--// ── Shape mirrors deeptutor/services/config/capabilities_settings.py ──────--interface SimpleLLMBlock {- temperature: number;- max_tokens: number;-}--interface ChatBlock {- temperature: number;- max_rounds: number;- stage_budgets: {- exploring: number;- responding: number;- };-}--interface ResearchExtras {- researching: {- note_agent_mode: string;- tool_timeout: number;- tool_max_retries: number;- paper_search_years_limit: number;- };-}--interface QuestionExtras {- exploring: {- max_iterations: number;- tool_summarizer: {- enabled: boolean;- max_tokens: number;- };- };-}--interface SolveExtras {- max_rounds: number;- max_replans: number;-}--interface CapabilitiesSettingsDTO {- chat: ChatBlock;- solve: SimpleLLMBlock & SolveExtras;- research: SimpleLLMBlock & ResearchExtras;- question: SimpleLLMBlock & QuestionExtras;- co_writer: SimpleLLMBlock;- vision_solver: SimpleLLMBlock;- math_animator: SimpleLLMBlock;-}--function isValidCapabilitiesDTO(- value: unknown,-): value is CapabilitiesSettingsDTO {- if (!value || typeof value !== "object") return false;- const v = value as Record<string, unknown>;- const chat = v.chat as Record<string, unknown> | undefined;- const solve = v.solve as Record<string, unknown> | undefined;- return (- !!chat &&- typeof chat.temperature === "number" &&- typeof chat.max_rounds === "number" &&- !!chat.stage_budgets &&- !!solve &&- typeof solve.max_rounds === "number" &&- typeof solve.max_replans === "number" &&- !!v.research &&- !!v.question- );-}--export default function CapabilitiesSettingsPage() {- const { t } = useTranslation();- const { registerExtension, pendingExtensionPayload, draftRevision } =- useSettings();- const [settings, setSettings] = useState<CapabilitiesSettingsDTO | null>(- null,- );- const [serverSnapshot, setServerSnapshot] =- useState<CapabilitiesSettingsDTO | null>(null);- const [loadError, setLoadError] = useState<string | null>(null);-- const load = useCallback(async () => {- try {- const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.capabilities));- if (!res.ok) {- setLoadError(- t(- "Failed to load capability settings (HTTP {{status}}). Make sure the backend is running the latest build — the /api/v1/capabilities/settings endpoint was added in this release.",- { status: res.status },- ),- );- return;- }- const data: unknown = await res.json();- if (!isValidCapabilitiesDTO(data)) {- setLoadError(- t(- "The backend returned an unexpected payload for /api/v1/capabilities/settings. Restart the backend to pick up the latest schema.",- ),- );- return;- }- const pending = pendingExtensionPayload("capabilities") as- | CapabilitiesSettingsDTO- | undefined;- setSettings(pending ?? data);- setServerSnapshot(data);- setLoadError(null);- } catch (err) {- setLoadError(- err instanceof Error- ? err.message- : t("Failed to load capability settings."),- );- }- }, [pendingExtensionPayload, t]);-- useEffect(() => {- const timer = window.setTimeout(() => {- void load();- }, 0);- return () => window.clearTimeout(timer);- // Re-read when a draft is discarded so the page drops its stale copy.- }, [draftRevision, load]);-- const dirty =- !!settings &&- !!serverSnapshot &&- JSON.stringify(settings) !== JSON.stringify(serverSnapshot);-- const settingsRef = useRef(settings);- useEffect(() => {- settingsRef.current = settings;- }, [settings]);- const save = useCallback(async () => {- const current = settingsRef.current;- if (!current) return;- const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.capabilities), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(current),- });- if (!res.ok) {- throw new Error(- t("Failed to save capability settings (HTTP {{status}})", {- status: res.status,- }),- );- }- const data: unknown = await res.json();- if (!isValidCapabilitiesDTO(data)) {- throw new Error(t("Backend returned an unexpected payload after save."));- }- setSettings(data);- setServerSnapshot(data);- }, [t]);-- useEffect(() => {- registerExtension("capabilities", { dirty, save, payload: settings });- return () => registerExtension("capabilities", null);- }, [dirty, save, settings, registerExtension]);-- function patchChat<K extends keyof ChatBlock>(key: K, value: ChatBlock[K]) {- if (!settings) return;- setSettings({ ...settings, chat: { ...settings.chat, [key]: value } });- }-- function patchStageBudget(- stage: keyof ChatBlock["stage_budgets"],- value: number,- ) {- if (!settings) return;- setSettings({- ...settings,- chat: {- ...settings.chat,- stage_budgets: { ...settings.chat.stage_budgets, [stage]: value },- },- });- }-- function patchSimple(- cap: "solve" | "co_writer" | "vision_solver" | "math_animator",- value: Partial<SimpleLLMBlock>,- ) {- if (!settings) return;- setSettings({ ...settings, [cap]: { ...settings[cap], ...value } });- }-- function patchSolveExtras(value: Partial<SolveExtras>) {- if (!settings) return;- setSettings({ ...settings, solve: { ...settings.solve, ...value } });- }-- function patchResearch(value: Partial<SimpleLLMBlock>) {- if (!settings) return;- setSettings({ ...settings, research: { ...settings.research, ...value } });- }-- function patchResearching(value: Partial<ResearchExtras["researching"]>) {- if (!settings) return;- setSettings({- ...settings,- research: {- ...settings.research,- researching: { ...settings.research.researching, ...value },- },- });- }-- function patchQuestion(value: Partial<SimpleLLMBlock>) {- if (!settings) return;- setSettings({ ...settings, question: { ...settings.question, ...value } });- }-- function patchExploring(value: Partial<QuestionExtras["exploring"]>) {- if (!settings) return;- setSettings({- ...settings,- question: {- ...settings.question,- exploring: { ...settings.question.exploring, ...value },- },- });- }-- function patchExploringSummarizer(- value: Partial<QuestionExtras["exploring"]["tool_summarizer"]>,- ) {- if (!settings) return;- setSettings({- ...settings,- question: {- ...settings.question,- exploring: {- ...settings.question.exploring,- tool_summarizer: {- ...settings.question.exploring.tool_summarizer,- ...value,- },- },- },- });- }-- if (loadError) {- return (- <div className="grid h-[60vh] place-items-center px-6">- <div className="max-w-xl rounded-lg border border-[var(--border)] bg-[var(--background)] p-4 text-[13px] text-[var(--muted-foreground)]">- <div className="mb-2 font-medium text-[var(--foreground)]">- {t("Couldn't load capability settings")}- </div>- <div>{loadError}</div>- <button- type="button"- onClick={() => void load()}- className="mt-3 rounded-md border border-[var(--border)] bg-[var(--card)] px-3 py-1 text-[12px] hover:bg-[var(--muted)]"- >- {t("Retry")}- </button>- </div>- </div>- );- }-- if (!settings) {- return (- <div className="grid h-[60vh] place-items-center text-[13px] text-[var(--muted-foreground)]">- <Loader2 className="h-4 w-4 animate-spin" />- </div>- );- }-- return (- <div data-tour="tour-capabilities">- <SettingsPageHeader- title={t("Capabilities")}- description={t("Per-capability LLM parameters and runtime knobs.")}- />-- <SettingSection- title={t("Chat")}- description={t(- "Exploring agent loop followed by a respond stage. Stage budgets cap max_tokens per LLM round.",- )}- >- <NumberRow- label={t("Temperature")}- help={t("Sampling temperature shared across every chat stage.")}- value={settings.chat.temperature}- onChange={(n) => patchChat("temperature", n)}- min={0}- max={2}- step={0.05}- isFloat- />- <NumberRow- label={t("Max rounds")}- help={t(- "Hard cap on exploring-loop LLM rounds per turn. A round without tool calls ends the loop early.",- )}- value={settings.chat.max_rounds}- onChange={(n) => patchChat("max_rounds", n)}- min={1}- max={50}- />- <NumberRow- label={t("Exploring (max tokens)")}- help={t("Budget per exploring-loop round (notes + tool calls).")}- value={settings.chat.stage_budgets.exploring}- onChange={(n) => patchStageBudget("exploring", n)}- min={256}- max={200000}- step={100}- />- <NumberRow- label={t("Responding (max tokens)")}- help={t("Budget for the final user-facing response.")}- value={settings.chat.stage_budgets.responding}- onChange={(n) => patchStageBudget("responding", n)}- min={256}- max={200000}- step={100}- />- </SettingSection>-- <SettingSection- title={t("Solve")}- description={t(- "Deep solve runs as one agent loop with a plan / finish-step / replan spine.",- )}- >- <NumberRow- label={t("Temperature")}- value={settings.solve.temperature}- onChange={(n) => patchSimple("solve", { temperature: n })}- min={0}- max={2}- step={0.05}- isFloat- />- <NumberRow- label={t("Max tokens")}- value={settings.solve.max_tokens}- onChange={(n) => patchSimple("solve", { max_tokens: n })}- min={256}- max={200000}- step={100}- />- <NumberRow- label={t("Max rounds")}- help={t(- "Total LLM-round budget for one solve turn (plan, tool calls and finishing all count).",- )}- value={settings.solve.max_rounds}- onChange={(n) => patchSolveExtras({ max_rounds: n })}- min={1}- max={50}- />- <NumberRow- label={t("Max replans")}- help={t(- "How many times the planner may revise the plan within one turn.",- )}- value={settings.solve.max_replans}- onChange={(n) => patchSolveExtras({ max_replans: n })}- min={0}- max={10}- />- </SettingSection>-- <SettingSection- title={t("Question")}- description={t("Deep question (quiz) generation pipeline.")}- >- <NumberRow- label={t("Temperature")}- value={settings.question.temperature}- onChange={(n) => patchQuestion({ temperature: n })}- min={0}- max={2}- step={0.05}- isFloat- />- <NumberRow- label={t("Max tokens")}- value={settings.question.max_tokens}- onChange={(n) => patchQuestion({ max_tokens: n })}- min={256}- max={200000}- step={100}- />- <NumberRow- label={t("Explore max iterations")}- help={t("Cap on the explore loop before planning.")}- value={settings.question.exploring.max_iterations}- onChange={(n) => patchExploring({ max_iterations: n })}- min={1}- max={50}- />- <ToggleRow- label={t("Tool summarizer enabled")}- help={t("Summarize long tool outputs to keep the prompt budget low.")}- value={settings.question.exploring.tool_summarizer.enabled}- onChange={(v) => patchExploringSummarizer({ enabled: v })}- />- <NumberRow- label={t("Tool summarizer (max tokens)")}- value={settings.question.exploring.tool_summarizer.max_tokens}- onChange={(n) => patchExploringSummarizer({ max_tokens: n })}- min={128}- max={200000}- step={100}- />- </SettingSection>-- <SettingSection- title={t("Research")}- description={t(- "Deep research pipeline. Iteration count is controlled per request via the depth selector (quick / standard / deep / manual) in the chat input, not here.",- )}- >- <NumberRow- label={t("Temperature")}- value={settings.research.temperature}- onChange={(n) => patchResearch({ temperature: n })}- min={0}- max={2}- step={0.05}- isFloat- />- <NumberRow- label={t("Max tokens")}- value={settings.research.max_tokens}- onChange={(n) => patchResearch({ max_tokens: n })}- min={256}- max={200000}- step={100}- />- <NumberRow- label={t("Tool timeout (s)")}- help={t("Per-tool wall-clock timeout for the researching phase.")}- value={settings.research.researching.tool_timeout}- onChange={(n) => patchResearching({ tool_timeout: n })}- min={1}- max={600}- />- <NumberRow- label={t("Tool max retries")}- value={settings.research.researching.tool_max_retries}- onChange={(n) => patchResearching({ tool_max_retries: n })}- min={0}- max={10}- />- <NumberRow- label={t("Paper search years limit")}- help={t("How far back paper search will scan.")}- value={settings.research.researching.paper_search_years_limit}- onChange={(n) => patchResearching({ paper_search_years_limit: n })}- min={1}- max={50}- />- </SettingSection>-- <SettingSection- title={t("Math animator")}- description={t("Manim animation / image generation pipeline.")}- >- <NumberRow- label={t("Temperature")}- value={settings.math_animator.temperature}- onChange={(n) => patchSimple("math_animator", { temperature: n })}- min={0}- max={2}- step={0.05}- isFloat- />- <NumberRow- label={t("Max tokens")}- value={settings.math_animator.max_tokens}- onChange={(n) => patchSimple("math_animator", { max_tokens: n })}- min={256}- max={200000}- step={100}- />- </SettingSection>-- <SettingSection- title={t("Co-writer")}- description={t("Selection edit / inline rewrite agent.")}- >- <NumberRow- label={t("Temperature")}- value={settings.co_writer.temperature}- onChange={(n) => patchSimple("co_writer", { temperature: n })}- min={0}- max={2}- step={0.05}- isFloat- />- <NumberRow- label={t("Max tokens")}- value={settings.co_writer.max_tokens}- onChange={(n) => patchSimple("co_writer", { max_tokens: n })}- min={256}- max={200000}- step={100}- />- </SettingSection>- </div>- );-}--// ── Field components (mirrors memory page) ─────────────────────────────--interface NumberRowProps {- label: string;- help?: string;- value: number;- onChange: (n: number) => void;- min?: number;- max?: number;- step?: number;- isFloat?: boolean;-}--function NumberRow({- label,- help,- value,- onChange,- min,- max,- step = 1,- isFloat = false,-}: NumberRowProps) {- return (- <SettingRow- title={label}- description={help}- control={- <input- type="number"- value={value}- min={min}- max={max}- step={step}- onChange={(e) => {- const raw = e.target.value;- if (raw === "") return;- const n = isFloat ? parseFloat(raw) : parseInt(raw, 10);- if (!Number.isNaN(n)) onChange(n);- }}- className="w-28 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-right text-[12px] outline-none focus:border-[var(--primary)]"- />- }- />- );-}--interface ToggleRowProps {- label: string;- help?: string;- value: boolean;- onChange: (v: boolean) => void;-}--function ToggleRow({ label, help, value, onChange }: ToggleRowProps) {- return (- <SettingRow- title={label}- description={help}- control={- <button- type="button"- role="switch"- aria-checked={value}- onClick={() => onChange(!value)}- className={- "relative inline-flex h-5 w-9 items-center rounded-full transition " +- (value ? "bg-[var(--primary)]" : "bg-[var(--muted)]")- }- >- <span- className={- "inline-block h-4 w-4 transform rounded-full bg-white shadow transition " +- (value ? "translate-x-4" : "translate-x-0.5")- }- />- </button>- }- />- );-}+export { default } from "@/features/settings/sections/CapabilitiesSettingsSection";diff --git a/web/app/(utility)/settings/chat/page.tsx b/web/app/(utility)/settings/chat/page.tsxindex 004e298e2..1e376fb8c 100644--- a/web/app/(utility)/settings/chat/page.tsx+++ b/web/app/(utility)/settings/chat/page.tsx@@ -1,26 +1 @@-"use client";--import { CategoryScroll } from "@/components/settings/CategoryScroll";--import VideoLearningSettingsPage from "../video-learning/page";-import ToolsSettingsPage from "../tools/page";-import CapabilitiesSettingsPage from "../capabilities/page";-import StarterSettingsPage from "../starters/page";-import AttachmentSettingsPage from "../attachments/page";--/**- * The Chat category, in full — see `ModelsSettingsPage` for the pattern.- */-export default function ChatSettingsPage() {- return (- <CategoryScroll- sections={[- { key: "video-learning", Component: VideoLearningSettingsPage },- { key: "tools", Component: ToolsSettingsPage },- { key: "capabilities", Component: CapabilitiesSettingsPage },- { key: "starters", Component: StarterSettingsPage },- { key: "attachments", Component: AttachmentSettingsPage },- ]}- />- );-}+export { default } from "@/features/settings/sections/ChatSettingsSection";diff --git a/web/app/(utility)/settings/connections/page.tsx b/web/app/(utility)/settings/connections/page.tsxindex b13545199..820159553 100644--- a/web/app/(utility)/settings/connections/page.tsx+++ b/web/app/(utility)/settings/connections/page.tsx@@ -1,21 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { ConnectionsEditor } from "@/components/settings/ConnectionsEditor";-import { SettingsPageHeader } from "@/components/settings/shared";--export default function ConnectionsSettingsPage() {- const { t } = useTranslation();- return (- <div>- <SettingsPageHeader- title={t("Connections")}- description={t(- "One vendor credential, supplying every model service that can use it. Services can still hold their own key instead.",- )}- />- <ConnectionsEditor />- </div>- );-}+export { default } from "@/features/settings/sections/models/ConnectionsSettingsSection";diff --git a/web/app/(utility)/settings/document-parsing/page.tsx b/web/app/(utility)/settings/document-parsing/page.tsxindex 6d5ae769a..3f343f308 100644--- a/web/app/(utility)/settings/document-parsing/page.tsx+++ b/web/app/(utility)/settings/document-parsing/page.tsx@@ -1,1404 +1 @@-"use client";--import { useCallback, useEffect, useRef, useState } from "react";-import { CheckCircle2, Download, Loader2, XCircle } from "lucide-react";-import { useTranslation } from "react-i18next";--import {- SettingRow,- SettingSection,- SettingsPageHeader,- inputClass,- nativeSelectClass,- selectOptionClass,-} from "@/components/settings/shared";-import { MinerUEngineSettings } from "@/components/settings/MinerUEngineSettings";-import { Toggle } from "@/components/settings/Toggle";-import { apiFetch, apiUrl } from "@/lib/api";--type EngineMeta = {- id: string;- name: string;- description: string;- needs_local_models: boolean;- available: boolean;-};--type Readiness = { ready: boolean; reason: string; message: string };--type DocumentParsingPayload = {- engine: string;- engines: Record<string, Record<string, unknown>>;- available_engines: EngineMeta[];- readiness: Record<string, Readiness>;- installable: string[];- mineru: { api_token_set: boolean; local_cli?: unknown };- docling?: { api_token_set: boolean };-};--const PIP_HINT: Record<string, string> = {- docling: "pip install deeptutor[parse-docling]",- markitdown: "pip install deeptutor[parse-markitdown]",- pymupdf4llm: "pip install deeptutor[parse-pymupdf4llm]",- liteparse: "pip install deeptutor[parse-liteparse]",-};--// Engine names and descriptions are returned by the backend so unknown or-// future engines can still render. Known descriptions use locale keys to keep-// the settings page translated without changing the API metadata contract.-const ENGINE_NAME_KEYS: Record<string, string> = {- text_only: "Text-only",-};--const ENGINE_DESCRIPTION_KEYS: Record<string, string> = {- text_only:- "Built-in plain text extraction for PDF/Office/text files. No optional parser package, no model download, no layout structure.",- mineru:- "Highest-fidelity multimodal parsing (layout, tables, formulas). Local CLI downloads models, or use the hosted cloud API. Supports PDF, common images, DOCX, PPTX, and XLSX.",- docling:- "Structured document conversion (layout/tables). Runs the in-process docling package (downloads models on first run) or points at a remote Docling Serve server. PDF/Office/HTML/images.",- markitdown:- "Lightweight, no model downloads — broad format support, Markdown output. Works out of the box.",- pymupdf4llm:- "Lightweight, no model downloads or CUDA — runs on low-end / GPU-less machines. PDF/e-book → Markdown and can extract images. PDF and e-book formats only.",- liteparse:- "Fast, lightweight PDF parser with spatial text extraction. Markdown output, optional image extraction. No model downloads. Developed by LlamaIndex.",- tika:- "Remote Apache Tika server. Broad format support, no local install or model downloads. Point at an existing tika-server container.",-};--export default function DocumentParsingSettingsPage() {- const { t } = useTranslation();- const [data, setData] = useState<DocumentParsingPayload | null>(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const [busy, setBusy] = useState(false);-- const load = useCallback(async () => {- setError(null);- try {- const response = await apiFetch(- apiUrl("/api/v1/settings/document-parsing"),- );- const payload = (await response.json().catch(() => ({}))) as- | DocumentParsingPayload- | { detail?: string };- if (!response.ok) {- throw new Error(- "detail" in payload && payload.detail- ? payload.detail- : t("Failed to load document parsing settings."),- );- }- setData(payload as DocumentParsingPayload);- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- } finally {- setLoading(false);- }- }, [t]);-- useEffect(() => {- void load();- }, [load]);-- const putDocumentParsing = useCallback(- async (body: Record<string, unknown>) => {- setBusy(true);- setError(null);- try {- const response = await apiFetch(- apiUrl("/api/v1/settings/document-parsing"),- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- },- );- const payload = (await response.json().catch(() => ({}))) as- | DocumentParsingPayload- | { detail?: string };- if (!response.ok) {- throw new Error(- "detail" in payload && payload.detail- ? payload.detail- : t("Failed to save document parsing settings."),- );- }- setData(payload as DocumentParsingPayload);- return true;- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- return false;- } finally {- setBusy(false);- }- },- [t],- );-- return (- <div>- <SettingsPageHeader- title={t("Document Parsing")}- description={t(- "How uploaded documents are converted into text for knowledge bases and question generation. Pick an engine and its options. Local model downloads are off by default — they only happen when you explicitly allow them.",- )}- />-- {loading && (- <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">- <Loader2 className="h-4 w-4 animate-spin" />- {t("Loading...")}- </div>- )}-- {!loading && error && (- <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">- {error}- </div>- )}-- {!loading && data && (- <>- <section className="mb-10">- <header className="mb-3">- <h2 className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">- {t("Engine")}- </h2>- <p className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">- {t(- "The active engine handles all parsing. Text-only is built in and extracts plain text; markitdown is lightweight and optional; MinerU and Docling produce richer structure, while Tika provides broad remote text extraction.",- )}- </p>- </header>- <div className="flex flex-col gap-2">- {data.available_engines.map((engine) => {- const active = engine.id === data.engine;- const nameKey = ENGINE_NAME_KEYS[engine.id];- const descriptionKey = ENGINE_DESCRIPTION_KEYS[engine.id];- return (- <button- key={engine.id}- type="button"- disabled={busy}- onClick={() =>- !active && putDocumentParsing({ engine: engine.id })- }- className={`flex items-start justify-between gap-4 rounded-xl border px-4 py-3 text-left transition-colors disabled:opacity-60 ${- active- ? "border-[var(--foreground)] bg-[var(--card)]"- : "border-[var(--border)] hover:border-[var(--foreground)]/40"- }`}- >- <div className="min-w-0">- <div className="flex items-center gap-2">- <span className="text-[13px] font-medium text-[var(--foreground)]">- {nameKey ? t(nameKey) : engine.name}- </span>- {active && (- <span className="rounded-full bg-[var(--foreground)] px-2 py-0.5 text-[10px] font-medium text-[var(--background)]">- {t("Active")}- </span>- )}- {!engine.available && (- <span className="rounded-full border border-[var(--border)] px-2 py-0.5 text-[10px] text-[var(--muted-foreground)]">- {t("Not installed")}- </span>- )}- </div>- <p className="mt-1 text-[12px] text-[var(--muted-foreground)]">- {descriptionKey ? t(descriptionKey) : engine.description}- </p>- </div>- </button>- );- })}- </div>- </section>-- {data.engine === "text_only" && <TextOnlyPanel />}-- {data.engine === "mineru" && <MinerUEngineSettings />}-- {data.engine === "docling" && (- <DoclingPanel- slice={data.engines.docling || {}}- readiness={data.readiness.docling}- available={- data.available_engines.find((e) => e.id === "docling")- ?.available ?? false- }- busy={busy}- onInstalled={load}- tokenSet={data.docling?.api_token_set ?? false}- onSave={(patch) =>- putDocumentParsing({ engines: { docling: patch } })- }- />- )}-- {data.engine === "markitdown" && (- <MarkItDownPanel- slice={data.engines.markitdown || {}}- available={- data.available_engines.find((e) => e.id === "markitdown")- ?.available ?? false- }- busy={busy}- onInstalled={load}- onSave={(patch) =>- putDocumentParsing({ engines: { markitdown: patch } })- }- />- )}-- {data.engine === "pymupdf4llm" && (- <PyMuPDF4LLMPanel- slice={data.engines.pymupdf4llm || {}}- available={- data.available_engines.find((e) => e.id === "pymupdf4llm")- ?.available ?? false- }- busy={busy}- onInstalled={load}- onSave={(patch) =>- putDocumentParsing({ engines: { pymupdf4llm: patch } })- }- />- )}-- {data.engine === "liteparse" && (- <LiteParsePanel- slice={data.engines.liteparse || {}}- available={- data.available_engines.find((e) => e.id === "liteparse")- ?.available ?? false- }- busy={busy}- onInstalled={load}- onSave={(patch) =>- putDocumentParsing({ engines: { liteparse: patch } })- }- />- )}-- {data.engine === "tika" && (- <TikaPanel- slice={data.engines.tika || {}}- readiness={data.readiness.tika}- busy={busy}- onSave={(patch) =>- putDocumentParsing({ engines: { tika: patch } })- }- />- )}- </>- )}- </div>- );-}--function TextOnlyPanel() {- const { t } = useTranslation();- return (- <SettingSection- title={t("Text-only")}- description={t(- "Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.",- )}- >- <SettingRow- title={t("Model status")}- control={- <ReadinessBadge- readiness={{ ready: true, reason: "ready", message: "" }}- />- }- />- </SettingSection>- );-}--function ReadinessBadge({ readiness }: { readiness?: Readiness }) {- const { t } = useTranslation();- if (!readiness) return null;- return (- <span- className={`inline-flex items-center gap-1 text-[12px] ${- readiness.ready- ? "text-emerald-600 dark:text-emerald-400"- : "text-amber-600 dark:text-amber-400"- }`}- >- {readiness.ready ? (- <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />- ) : (- <XCircle className="h-3.5 w-3.5 shrink-0" />- )}- {readiness.ready ? t("Ready to parse.") : t(readiness.message)}- </span>- );-}--// Full-width readiness line for engines whose "not ready" guidance is a-// multi-sentence message (e.g. Docling's "models not downloaded" hint). A long-// message must wrap full-width — it doesn't fit a SettingRow's compact,-// non-shrinking control slot (which overflows and squeezes the title).-function ReadinessNotice({ readiness }: { readiness?: Readiness }) {- const { t } = useTranslation();- if (!readiness) return null;- if (readiness.ready) {- return (- <div className="flex items-center gap-1.5 py-3.5 text-[12px] text-emerald-600 dark:text-emerald-400">- <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />- {t("Ready to parse.")}- </div>- );- }- return (- <div className="py-3.5">- <div className="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[12px] leading-relaxed text-amber-700 dark:text-amber-300">- <XCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />- <span className="min-w-0">{t(readiness.message)}</span>- </div>- </div>- );-}--const DOCLING_MODES = ["local", "remote"] as const;-const DEFAULT_DOCLING_URL = "http://localhost:5001";-const TOKEN_MASK = "••••••••••••";--function DoclingPanel({- slice,- readiness,- available,- busy,- tokenSet,- onInstalled,- onSave,-}: {- slice: Record<string, unknown>;- readiness?: Readiness;- available: boolean;- busy: boolean;- tokenSet: boolean;- onInstalled: () => void;- onSave: (patch: Record<string, unknown>) => Promise<boolean>;-}) {- const { t } = useTranslation();- const mode =- slice.mode === "remote"- ? "remote"- : slice.mode === "local"- ? "local"- : "local";- const isRemote = mode === "remote";- const doOcr = Boolean(slice.do_ocr);- const doTables = slice.do_table_structure !== false;- const allowDownload = Boolean(slice.allow_local_model_download);-- // Remote server URL + API key are edited as a draft and saved together so a- // half-typed URL is never used mid-parse. Token is write-only.- const [remoteDraft, setRemoteDraft] = useState({- url: (typeof slice.api_base_url === "string" && slice.api_base_url) || "",- });- const [tokenDraft, setTokenDraft] = useState("");- const [tokenTouched, setTokenTouched] = useState(false);- const [savingRemote, setSavingRemote] = useState(false);- const [testing, setTesting] = useState(false);- const [testResult, setTestResult] = useState<{- ok: boolean;- message: string;- } | null>(null);- const [remoteMsg, setRemoteMsg] = useState("");-- async function saveRemote() {- setSavingRemote(true);- setRemoteMsg("");- setTestResult(null);- const patch: Record<string, unknown> = {- mode: "remote",- api_base_url: remoteDraft.url.trim() || DEFAULT_DOCLING_URL,- };- if (tokenTouched) patch.api_token = tokenDraft;- try {- const saved = await onSave(patch);- if (saved) {- setRemoteMsg(t("Remote Docling settings saved."));- setTokenDraft("");- setTokenTouched(false);- }- } finally {- setSavingRemote(false);- }- }-- async function testConnection() {- setTesting(true);- setTestResult(null);- try {- const body: Record<string, unknown> = {- api_base_url: remoteDraft.url.trim() || DEFAULT_DOCLING_URL,- };- if (tokenTouched) body.api_token = tokenDraft;- const response = await apiFetch(- apiUrl("/api/v1/settings/document-parsing/docling/test"),- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- },- );- const data = (await response.json().catch(() => ({}))) as {- ok?: boolean;- message?: string;- detail?: string;- };- if (!response.ok) {- setTestResult({- ok: false,- message: data.detail || t("Connection test failed."),- });- return;- }- setTestResult({- ok: Boolean(data.ok),- message:- data.message ||- (data.ok ? t("Ready to parse.") : t("Connection test failed.")),- });- } catch (err) {- setTestResult({- ok: false,- message: err instanceof Error ? err.message : String(err),- });- } finally {- setTesting(false);- }- }-- const notInstalled = !available && !isRemote;-- return (- <>- <SettingSection- title={t("Docling backend")}- description={t(- "Choose where parsing runs: the in-process docling package (local) or a Docling Serve server (remote).",- )}- >- <SettingRow- title={t("Mode")}- description={- isRemote- ? t(- "Documents are sent to a Docling Serve server for conversion.",- )- : t(- "Parsing runs on this machine using the installed docling package.",- )- }- control={- <div className="inline-flex rounded-lg border border-[var(--border)] p-0.5">- {DOCLING_MODES.map((m) => (- <button- key={m}- type="button"- disabled={busy}- onClick={() => {- if (m !== mode) {- onSave({ mode: m });- setTestResult(null);- }- }}- className={`rounded-md px-3 py-1 text-[12px] font-medium transition-colors disabled:opacity-40 ${- mode === m- ? "bg-[var(--foreground)] text-[var(--background)]"- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- {m === "local" ? t("Local") : t("Remote server")}- </button>- ))}- </div>- }- />- </SettingSection>-- {isRemote && (- <SettingSection- title={t("Remote server")}- description={t(- "Point at a Docling Serve server (e.g. `docling serve` or the docker image). No local docling install or models needed.",- )}- >- <SettingRow- title={t("Server base URL")}- control={- <input- className={`${inputClass} w-[320px] max-w-[48vw] font-mono text-[12px]`}- placeholder={DEFAULT_DOCLING_URL}- value={remoteDraft.url}- onChange={(e) => {- setRemoteDraft({ url: e.target.value });- setTestResult(null);- }}- />- }- />- <SettingRow- title={t("API key")}- description={- tokenSet- ? t(- "A key is saved. Type to replace it; leave blank to keep it.",- )- : t(- "Optional. Sent as the X-Api-Key header for a secured server.",- )- }- control={- <input- type="password"- className={`${inputClass} w-[320px] max-w-[48vw]`}- placeholder={tokenSet ? TOKEN_MASK : t("Optional API key")}- value={tokenDraft}- onChange={(e) => {- setTokenDraft(e.target.value);- setTokenTouched(true);- }}- />- }- />- <SettingRow- title={t("Test connection")}- description={t("Pings the server health + version endpoints.")}- control={- <div className="flex items-center gap-3">- {testResult && (- <span- className={`inline-flex max-w-[40vw] items-center gap-1 text-[12px] ${- testResult.ok- ? "text-emerald-600 dark:text-emerald-400"- : "text-red-600 dark:text-red-400"- }`}- >- {testResult.ok ? (- <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />- ) : (- <XCircle className="h-3.5 w-3.5 shrink-0" />- )}- {testResult.message}- </span>- )}- <button- type="button"- onClick={testConnection}- disabled={testing || savingRemote || busy}- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-opacity hover:opacity-80 disabled:opacity-40"- >- {testing && <Loader2 className="h-3 w-3 animate-spin" />}- {t("Test")}- </button>- <button- type="button"- onClick={saveRemote}- disabled={savingRemote || busy}- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"- >- {savingRemote && <Loader2 className="h-3 w-3 animate-spin" />}- {t("Save remote server")}- </button>- </div>- }- />- <div className="px-1 pb-4">- <span className="text-[12px] text-[var(--muted-foreground)]">- {remoteMsg ||- t(- "Settings are written to data/user/settings/document_parsing.json.",- )}- </span>- </div>- </SettingSection>- )}-- {isRemote && (- <SettingSection- title={t("Parsing options")}- description={t("Forwarded to the Docling server for each document.")}- >- <SettingRow- title={t("Recognize tables")}- control={- <Toggle- checked={doTables}- disabled={busy}- onChange={(v) => onSave({ do_table_structure: v })}- />- }- />- <SettingRow- title={t("OCR scanned pages")}- description={t("Slower; enable for image-only PDFs.")}- control={- <Toggle- checked={doOcr}- disabled={busy}- onChange={(v) => onSave({ do_ocr: v })}- />- }- />- </SettingSection>- )}-- {!isRemote && notInstalled && (- <NotInstalledSection- engineId="docling"- title={t("Docling (local)")}- onInstalled={onInstalled}- />- )}-- {!isRemote && !notInstalled && (- <SettingSection- title={t("Docling (local)")}- description={t(- "Structured conversion of PDF/Office/HTML/images. Downloads layout/table models on first run.",- )}- >- <ReadinessNotice readiness={readiness} />- {readiness && !readiness.ready && (- <ModelDownloadRow- engineId="docling"- title={t("Docling")}- onDownloaded={onInstalled}- />- )}- <SettingRow- title={t("Allow automatic model download")}- description={t(- "Off by default. When off, parsing fails with guidance instead of silently downloading models. Or pre-fetch with `docling-tools models download`.",- )}- control={- <Toggle- checked={allowDownload}- disabled={busy}- onChange={(v) => onSave({ allow_local_model_download: v })}- />- }- />- <SettingRow- title={t("Recognize tables")}- control={- <Toggle- checked={doTables}- disabled={busy}- onChange={(v) => onSave({ do_table_structure: v })}- />- }- />- <SettingRow- title={t("OCR scanned pages")}- description={t("Slower; enable for image-only PDFs.")}- control={- <Toggle- checked={doOcr}- disabled={busy}- onChange={(v) => onSave({ do_ocr: v })}- />- }- />- </SettingSection>- )}- </>- );-}--const DEFAULT_TIKA_URL = "http://localhost:9998";--function TikaPanel({- slice,- readiness,- busy,- onSave,-}: {- slice: Record<string, unknown>;- readiness?: Readiness;- busy: boolean;- onSave: (patch: Record<string, unknown>) => Promise<boolean>;-}) {- const { t } = useTranslation();- const [draftUrl, setDraftUrl] = useState(- (typeof slice.server_url === "string" && slice.server_url) || "",- );- const [saving, setSaving] = useState(false);- const [testing, setTesting] = useState(false);- const [testResult, setTestResult] = useState<{- ok: boolean;- message: string;- } | null>(null);-- async function save() {- setSaving(true);- setTestResult(null);- try {- await onSave({ server_url: draftUrl.trim() || DEFAULT_TIKA_URL });- } finally {- setSaving(false);- }- }-- async function testConnection() {- setTesting(true);- setTestResult(null);- try {- const response = await apiFetch(- apiUrl("/api/v1/settings/document-parsing/tika/test"),- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- server_url: draftUrl.trim() || DEFAULT_TIKA_URL,- }),- },- );- const data = (await response.json().catch(() => ({}))) as {- ok?: boolean;- message?: string;- detail?: string;- };- if (!response.ok) {- setTestResult({- ok: false,- message: data.detail || t("Connection test failed."),- });- return;- }- setTestResult({- ok: Boolean(data.ok),- message:- data.message ||- (data.ok ? t("Ready to parse.") : t("Connection test failed.")),- });- } catch (err) {- setTestResult({- ok: false,- message: err instanceof Error ? err.message : String(err),- });- } finally {- setTesting(false);- }- }-- return (- <SettingSection- title={t("Tika")}- description={t(- "Point at an Apache Tika server (e.g. the apache/tika docker image). No local install or models needed.",- )}- >- <ReadinessNotice readiness={readiness} />- <SettingRow- title={t("Server base URL")}- control={- <input- className={`${inputClass} w-[320px] max-w-[48vw] font-mono text-[12px]`}- placeholder={DEFAULT_TIKA_URL}- value={draftUrl}- onChange={(e) => {- setDraftUrl(e.target.value);- setTestResult(null);- }}- />- }- />- <SettingRow- title={t("Test connection")}- description={t("Pings the server /version endpoint.")}- control={- <div className="flex items-center gap-3">- {testResult && (- <span- className={`inline-flex max-w-[40vw] items-center gap-1 text-[12px] ${- testResult.ok- ? "text-emerald-600 dark:text-emerald-400"- : "text-red-600 dark:text-red-400"- }`}- >- {testResult.ok ? (- <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />- ) : (- <XCircle className="h-3.5 w-3.5 shrink-0" />- )}- {testResult.message}- </span>- )}- <button- type="button"- onClick={testConnection}- disabled={testing || saving || busy}- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-opacity hover:opacity-80 disabled:opacity-40"- >- {testing && <Loader2 className="h-3 w-3 animate-spin" />}- {t("Test")}- </button>- <button- type="button"- onClick={save}- disabled={saving || busy}- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"- >- {saving && <Loader2 className="h-3 w-3 animate-spin" />}- {t("Save Tika server")}- </button>- </div>- }- />- <div className="px-1 pb-4">- <span className="text-[12px] text-[var(--muted-foreground)]">- {t(- "Settings are written to data/user/settings/document_parsing.json.",- )}- </span>- </div>- </SettingSection>- );-}--function MarkItDownPanel({- slice,- available,- busy,- onInstalled,- onSave,-}: {- slice: Record<string, unknown>;- available: boolean;- busy: boolean;- onInstalled: () => void;- onSave: (patch: Record<string, unknown>) => void;-}) {- const { t } = useTranslation();- const llmImages = Boolean(slice.enable_llm_image_description);-- if (!available) {- return (- <NotInstalledSection- engineId="markitdown"- title={t("markitdown")}- onInstalled={onInstalled}- />- );- }-- return (- <SettingSection- title={t("markitdown")}- description={t(- "Lightweight Markdown conversion with broad format support. No model downloads.",- )}- >- <SettingRow- title={t("Describe images with the vision model")}- description={t(- "Reserved — uses DeepTutor's vision model to caption images during conversion.",- )}- control={- <Toggle- checked={llmImages}- disabled={busy}- onChange={(v) => onSave({ enable_llm_image_description: v })}- />- }- />- </SettingSection>- );-}--const PYMUPDF4LLM_IMAGE_FORMATS = ["png", "jpg", "jpeg", "webp"];--function PyMuPDF4LLMPanel({- slice,- available,- busy,- onInstalled,- onSave,-}: {- slice: Record<string, unknown>;- available: boolean;- busy: boolean;- onInstalled: () => void;- onSave: (patch: Record<string, unknown>) => void;-}) {- const { t } = useTranslation();- const writeImages = slice.write_images !== false;- const imageFormat =- typeof slice.image_format === "string" ? slice.image_format : "png";- const imageDpi = typeof slice.image_dpi === "number" ? slice.image_dpi : 150;-- if (!available) {- return (- <NotInstalledSection- engineId="pymupdf4llm"- title={t("PyMuPDF4LLM")}- onInstalled={onInstalled}- />- );- }-- return (- <SettingSection- title={t("PyMuPDF4LLM")}- description={t(- "Lightweight PDF/e-book → Markdown built on PyMuPDF. No model downloads or CUDA, so it runs on low-end machines.",- )}- >- <SettingRow- title={t("Extract images")}- description={t(- "Save embedded images and rendered vector graphics into the parse, referenced from the Markdown.",- )}- control={- <Toggle- checked={writeImages}- disabled={busy}- onChange={(v) => onSave({ write_images: v })}- />- }- />- {writeImages && (- <>- <SettingRow- title={t("Image format")}- control={- <select- className={`${nativeSelectClass} w-28`}- value={imageFormat}- disabled={busy}- onChange={(e) => onSave({ image_format: e.target.value })}- >- {PYMUPDF4LLM_IMAGE_FORMATS.map((f) => (- <option key={f} className={selectOptionClass} value={f}>- {f}- </option>- ))}- </select>- }- />- <SettingRow- title={t("Image resolution (DPI)")}- description={t("Higher is sharper but larger. 72–600.")}- control={- <input- type="number"- min={72}- max={600}- step={1}- value={imageDpi}- disabled={busy}- onChange={(e) => {- const v = Number(e.target.value);- if (Number.isFinite(v)) onSave({ image_dpi: v });- }}- className="w-24 rounded-lg border border-[var(--border)] bg-transparent px-2 py-1 text-[12px] text-[var(--foreground)]"- />- }- />- </>- )}- </SettingSection>- );-}--function LiteParsePanel({- slice,- available,- busy,- onInstalled,- onSave,-}: {- slice: Record<string, unknown>;- available: boolean;- busy: boolean;- onInstalled: () => void;- onSave: (patch: Record<string, unknown>) => void;-}) {- const { t } = useTranslation();- const imageMode =- typeof slice.image_mode === "string" ? slice.image_mode : "placeholder";- const extractLinks = slice.extract_links !== false;- const extractImages = Boolean(slice.extract_images);- const maxPages = typeof slice.max_pages === "number" ? slice.max_pages : 0;-- if (!available) {- return (- <NotInstalledSection- engineId="liteparse"- title={t("LiteParse")}- onInstalled={onInstalled}- />- );- }-- return (- <SettingSection- title={t("LiteParse")}- description={t(- "Fast Rust-backed PDF/Office/image parser from LlamaIndex. Markdown output, no model downloads.",- )}- >- <SettingRow- title={t("Image mode")}- description={t("How images are represented in the output.")}- control={- <select- className={nativeSelectClass + " w-32"}- value={imageMode}- disabled={busy}- onChange={(e) => onSave({ image_mode: e.target.value })}- >- {["placeholder", "off", "embed"].map((m) => (- <option key={m} className={selectOptionClass} value={m}>- {m}- </option>- ))}- </select>- }- />- <SettingRow- title={t("Extract links")}- description={t("Render [text](url) links in markdown output.")}- control={- <Toggle- checked={extractLinks}- disabled={busy}- onChange={(v) => onSave({ extract_links: v })}- />- }- />- <SettingRow- title={t("Extract images")}- description={t("Save embedded images alongside the parsed Markdown.")}- control={- <Toggle- checked={extractImages}- disabled={busy}- onChange={(v) => onSave({ extract_images: v })}- />- }- />- <SettingRow- title={t("Max pages")}- description={t("0 = unlimited. Limit pages parsed per document.")}- control={- <input- type="number"- min={0}- step={1}- value={maxPages}- disabled={busy}- onChange={(e) => {- const v = Number(e.target.value);- if (Number.isFinite(v) && v >= 0) onSave({ max_pages: v });- }}- className="w-24 rounded-lg border border-[var(--border)] bg-transparent px-2 py-1 text-[12px] text-[var(--foreground)]"- />- }- />- </SettingSection>- );-}--type JobKind = "install" | "models";--type JobStatus = {- state: "running" | "done" | "failed" | "cancelled" | string;- kind: JobKind;- lines: string[];- message: string;-};--// Shared driver for the page's one-click background jobs (pip install / model-// download). Mirrors the MinerU model-download UI: POST to start → poll a shared-// cursor-based log filtered by `kind` → call onDone once on success. Only one-// job runs server-side at a time, so the kind filter keeps each card's view to-// its own job.-function useBackgroundJob(- kind: JobKind,- startUrl: string,- engineId: string,- onDone: () => void,-) {- const { t } = useTranslation();- const [job, setJob] = useState<JobStatus | null>(null);- const [starting, setStarting] = useState(false);- const cursor = useRef(0);- const notifiedDone = useRef(false);-- useEffect(() => {- if (job?.state !== "running") return;- const timer = setInterval(async () => {- try {- const response = await apiFetch(- apiUrl(- `/api/v1/settings/document-parsing/job/status?cursor=${cursor.current}`,- ),- );- if (!response.ok) return;- const data = (await response.json()) as {- state?: string;- kind?: string;- lines?: string[];- next_cursor?: number;- message?: string;- };- // A different kind of job is running — leave our view alone.- if (data.kind && data.kind !== kind) return;- cursor.current = data.next_cursor ?? cursor.current;- setJob((current) =>- current- ? {- state: data.state || current.state,- kind,- lines: [...current.lines, ...(data.lines || [])].slice(-100),- message: data.message || "",- }- : current,- );- if (data.state === "done" && !notifiedDone.current) {- notifiedDone.current = true;- onDone();- }- } catch {- // transient network error — keep polling- }- }, 1000);- return () => clearInterval(timer);- }, [job?.state, kind, onDone]);-- async function start() {- setStarting(true);- notifiedDone.current = false;- try {- const response = await apiFetch(apiUrl(startUrl), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ engine: engineId }),- });- const data = (await response.json().catch(() => ({}))) as {- ok?: boolean;- message?: string;- detail?: string;- };- if (!response.ok || !data.ok) {- setJob({- state: "failed",- kind,- lines: [],- message: data.message || data.detail || t("Failed."),- });- return;- }- cursor.current = 0;- setJob({ state: "running", kind, lines: [], message: "" });- } finally {- setStarting(false);- }- }-- async function cancel() {- try {- await apiFetch(apiUrl("/api/v1/settings/document-parsing/job/cancel"), {- method: "POST",- });- } catch {- // status polling surfaces the final state either way- }- }-- return { job, starting, start, cancel };-}--// Status line + streamed log for a background job, shared by install / download.-function JobLog({- job,- runningLabel,- doneLabel,-}: {- job: JobStatus | null;- runningLabel: string;- doneLabel: string;-}) {- if (!job) return null;- return (- <div className="px-1 pb-1">- <div- className={`mb-2 inline-flex items-center gap-1.5 text-[12px] ${- job.state === "done"- ? "text-emerald-600 dark:text-emerald-400"- : job.state === "running"- ? "text-[var(--muted-foreground)]"- : "text-red-600 dark:text-red-400"- }`}- >- {job.state === "running" ? (- <Loader2 className="h-3 w-3 animate-spin" />- ) : job.state === "done" ? (- <CheckCircle2 className="h-3.5 w-3.5" />- ) : (- <XCircle className="h-3.5 w-3.5" />- )}- {job.state === "running"- ? runningLabel- : job.state === "done"- ? doneLabel- : job.message || job.state}- </div>- {job.lines.length > 0 && (- <pre className="max-h-40 overflow-y-auto whitespace-pre-wrap rounded-lg border border-[var(--border)]/60 bg-[var(--card)] px-3 py-2 font-mono text-[11px] leading-relaxed text-[var(--muted-foreground)]">- {job.lines.join("\n")}- </pre>- )}- </div>- );-}--function JobButton({- running,- starting,- label,- onStart,- onCancel,-}: {- running: boolean;- starting: boolean;- label: string;- onStart: () => void;- onCancel: () => void;-}) {- const { t } = useTranslation();- if (running) {- return (- <button- type="button"- onClick={onCancel}- className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-opacity hover:opacity-80"- >- {t("Cancel")}- </button>- );- }- return (- <button- type="button"- onClick={onStart}- disabled={starting}- className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"- >- {starting ? (- <Loader2 className="h-3 w-3 animate-spin" />- ) : (- <Download className="h-3 w-3" />- )}- {label}- </button>- );-}--// The active engine's panel when its optional package isn't installed: a clean-// section with the pip hint and a one-click installer. Keeps install in ONE-// place per engine; reloads on success so the engine flips to available.-function NotInstalledSection({- engineId,- title,- onInstalled,-}: {- engineId: string;- title: string;- onInstalled: () => void;-}) {- const { t } = useTranslation();- const { job, starting, start, cancel } = useBackgroundJob(- "install",- "/api/v1/settings/document-parsing/install",- engineId,- onInstalled,- );-- return (- <SettingSection- title={title}- description={t(- "Not installed yet. Install the package to use this engine — runs on the server, no terminal needed.",- )}- >- <SettingRow- title={t("Install package")}- description={PIP_HINT[engineId]}- control={- <JobButton- running={job?.state === "running"}- starting={starting}- label={t("Download & install")}- onStart={start}- onCancel={cancel}- />- }- />- <JobLog- job={job}- runningLabel={t("Installing {{name}}…", { name: title })}- doneLabel={t("Installed. Reloading…")}- />- </SettingSection>- );-}--// One-click model-weight download for an installed engine that still needs its-// models (e.g. Docling). Mirrors MinerU's "Download models"; reloads readiness-// on success so the gate clears.-function ModelDownloadRow({- engineId,- title,- onDownloaded,-}: {- engineId: string;- title: string;- onDownloaded: () => void;-}) {- const { t } = useTranslation();- const { job, starting, start, cancel } = useBackgroundJob(- "models",- "/api/v1/settings/document-parsing/models/download",- engineId,- onDownloaded,- );-- return (- <>- <SettingRow- title={t("Download models")}- description={t(- "Fetch the model weights onto the server now — no terminal needed.",- )}- control={- <JobButton- running={job?.state === "running"}- starting={starting}- label={t("Download models")}- onStart={start}- onCancel={cancel}- />- }- />- <JobLog- job={job}- runningLabel={t("Downloading {{name}} models…", { name: title })}- doneLabel={t("Downloaded. Reloading…")}- />- </>- );-}+export { default } from "@/features/settings/sections/DocumentParsingSettingsSection";diff --git a/web/app/(utility)/settings/embedding/page.tsx b/web/app/(utility)/settings/embedding/page.tsxindex 71a59b96a..a00dde899 100644--- a/web/app/(utility)/settings/embedding/page.tsx+++ b/web/app/(utility)/settings/embedding/page.tsx@@ -1,21 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";-import { SettingsPageHeader } from "@/components/settings/shared";--export default function EmbeddingSettingsPage() {- const { t } = useTranslation();- return (- <div>- <SettingsPageHeader- title={t("Embedding")}- description={t(- "Configure embedding model profiles. Used by retrieval and knowledge-base ingestion.",- )}- />- <ServiceConfigEditor service="embedding" />- </div>- );-}+export { default } from "@/features/settings/sections/models/EmbeddingSettingsSection";diff --git a/web/app/(utility)/settings/image/page.tsx b/web/app/(utility)/settings/image/page.tsxindex b5a92c9b2..3b4af503a 100644--- a/web/app/(utility)/settings/image/page.tsx+++ b/web/app/(utility)/settings/image/page.tsx@@ -1,21 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";-import { SettingsPageHeader } from "@/components/settings/shared";--export default function ImageGenSettingsPage() {- const { t } = useTranslation();- return (- <div>- <SettingsPageHeader- title={t("Image Generation")}- description={t(- "Text-to-image model used by the chat 'imagegen' tool. Works with any OpenAI-compatible /images/generations API — OpenAI, Volcengine Seedream, or compatible gateways.",- )}- />- <ServiceConfigEditor service="imagegen" />- </div>- );-}+export { default } from "@/features/settings/sections/models/ImageSettingsSection";diff --git a/web/app/(utility)/settings/layout.tsx b/web/app/(utility)/settings/layout.tsxindex 23fdc4de2..bc556fc2b 100644--- a/web/app/(utility)/settings/layout.tsx+++ b/web/app/(utility)/settings/layout.tsx@@ -1,5 +1,10 @@import SettingsMain from "@/components/settings/SettingsMain";-import { SettingsProvider } from "@/components/settings/SettingsContext";+import {+ ModelCatalogProvider,+ SettingsDraftProvider,+ SettingsProvider,+ UiSettingsProvider,+} from "@/features/settings/store";import { SettingsTourOverlay } from "@/components/settings/SettingsTourOverlay";export default function SettingsLayout({@@ -9,10 +14,16 @@ export default function SettingsLayout({}>) {return (<SettingsProvider>- <SettingsMain>{children}</SettingsMain>- {/* Mounted once at the layout level so the cross-route guided tour- survives navigation between the hub and its sub-pages. */}- <SettingsTourOverlay />+ <UiSettingsProvider>+ <ModelCatalogProvider>+ <SettingsDraftProvider>+ <SettingsMain>{children}</SettingsMain>+ {/* Mounted once at the layout level so the cross-route guided tour+ survives navigation between the hub and its sub-pages. */}+ <SettingsTourOverlay />+ </SettingsDraftProvider>+ </ModelCatalogProvider>+ </UiSettingsProvider></SettingsProvider>);}diff --git a/web/app/(utility)/settings/llm/page.tsx b/web/app/(utility)/settings/llm/page.tsxindex b7aacbde5..ffe7364a7 100644--- a/web/app/(utility)/settings/llm/page.tsx+++ b/web/app/(utility)/settings/llm/page.tsx@@ -1,21 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";-import { SettingsPageHeader } from "@/components/settings/shared";--export default function LlmSettingsPage() {- const { t } = useTranslation();- return (- <div>- <SettingsPageHeader- title={t("LLM")}- description={t(- "Configure language model profiles. The active model is used for chat and most agent reasoning.",- )}- />- <ServiceConfigEditor service="llm" />- </div>- );-}+export { default } from "@/features/settings/sections/models/LlmSettingsSection";diff --git a/web/app/(utility)/settings/memory/page.tsx b/web/app/(utility)/settings/memory/page.tsxindex 11c204802..280ed7d32 100644--- a/web/app/(utility)/settings/memory/page.tsx+++ b/web/app/(utility)/settings/memory/page.tsx@@ -1,393 +1 @@-"use client";--import { useCallback, useEffect, useRef, useState } from "react";-import { Loader2 } from "lucide-react";-import { useTranslation } from "react-i18next";--import { apiFetch, apiUrl } from "@/lib/api";-import { EXTENSION_ENDPOINTS } from "@/lib/settings-extensions";-import {- SettingRow,- SettingSection,- SettingsPageHeader,-} from "@/components/settings/shared";-import { useSettings } from "@/components/settings/SettingsContext";--interface MemorySettingsDTO {- update: { l2_budget: number; l3_budget: number };- audit: { l2_budget: number; l3_budget: number };- dedup: { iterations: number; auto_after_update: boolean };- merge: {- auto_after_update: boolean;- auto_after_audit: boolean;- auto_after_dedup: boolean;- };- chunking: {- overlap_ratio: number;- boundary: "paragraph" | "sentence";- min_chunk_chars: number;- max_chunk_chars: number;- };- reference: {- enforce_required: boolean;- drop_invalid_refs: boolean;- };-}--export default function MemorySettingsPage() {- const { t } = useTranslation();- const { registerExtension, pendingExtensionPayload, draftRevision } =- useSettings();- const [settings, setSettings] = useState<MemorySettingsDTO | null>(null);- const [serverSnapshot, setServerSnapshot] =- useState<MemorySettingsDTO | null>(null);-- useEffect(() => {- let cancelled = false;- void apiFetch(apiUrl(EXTENSION_ENDPOINTS.memory))- .then((res) => res.json() as Promise<MemorySettingsDTO>)- .then((data) => {- if (cancelled) return;- // A pending edit outlives the page it was made on; the server value is- // the baseline dirtiness is measured against either way.- const pending = pendingExtensionPayload("memory") as- | MemorySettingsDTO- | undefined;- setSettings(pending ?? data);- setServerSnapshot(data);- });- return () => {- cancelled = true;- };- }, [draftRevision, pendingExtensionPayload]);-- const dirty =- !!settings &&- !!serverSnapshot &&- JSON.stringify(settings) !== JSON.stringify(serverSnapshot);-- // Latest-save ref so the closure handed to registerExtension always- // reflects the current settings without re-registering on each render.- const settingsRef = useRef<MemorySettingsDTO | null>(null);- useEffect(() => {- settingsRef.current = settings;- }, [settings]);- const save = useCallback(async () => {- const current = settingsRef.current;- if (!current) return;- const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.memory), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(current),- });- const data = (await res.json()) as MemorySettingsDTO;- setSettings(data);- setServerSnapshot(data);- }, []);-- useEffect(() => {- registerExtension("memory", { dirty, save, payload: settings });- return () => registerExtension("memory", null);- }, [dirty, save, settings, registerExtension]);-- function patch<K extends keyof MemorySettingsDTO>(- key: K,- value: Partial<MemorySettingsDTO[K]>,- ) {- if (!settings) return;- setSettings({ ...settings, [key]: { ...settings[key], ...value } });- }-- if (!settings) {- return (- <div className="grid h-[60vh] place-items-center text-[13px] text-[var(--muted-foreground)]">- <Loader2 className="h-4 w-4 animate-spin" />- </div>- );- }-- return (- <div data-tour="tour-memory">- <SettingsPageHeader- title={t("Memory")}- description={t(- "Tune the chunk-based consolidator: how many LLM rounds per Update / Audit / Dedup, how aggressively to chunk, and how strictly to validate references.",- )}- />- <SettingSection- title={t("Update mode")}- description={t(- "Default LLM rounds for chunk-based incremental fact extraction. Per-doc overrides live in the workbench.",- )}- >- <NumberRow- label={t("L2 budget (per surface)")}- help={t("Maximum chunks the chunker emits for an L2 update.")}- value={settings.update.l2_budget}- onChange={(n) => patch("update", { l2_budget: n })}- min={1}- max={200}- />- <NumberRow- label={t("L3 budget (per slot)")}- help={t("Maximum chunks for an L3 update across the 7 L2 docs.")}- value={settings.update.l3_budget}- onChange={(n) => patch("update", { l3_budget: n })}- min={1}- max={200}- />- </SettingSection>-- <SettingSection- title={t("Audit mode")}- description={t(- "Default LLM rounds for line-level edits against raw evidence.",- )}- >- <NumberRow- label={t("L2 budget (per surface)")}- value={settings.audit.l2_budget}- onChange={(n) => patch("audit", { l2_budget: n })}- min={1}- max={200}- />- <NumberRow- label={t("L3 budget (per slot)")}- value={settings.audit.l3_budget}- onChange={(n) => patch("audit", { l3_budget: n })}- min={1}- max={200}- />- </SettingSection>-- <SettingSection- title={t("Dedup")}- description={t(- "Iterative dedup over the full doc. Stops early when an iteration emits zero edits.",- )}- >- <NumberRow- label={t("Iterations")}- value={settings.dedup.iterations}- onChange={(n) => patch("dedup", { iterations: n })}- min={1}- max={20}- />- <ToggleRow- label={t("Run dedup automatically after Update")}- value={settings.dedup.auto_after_update}- onChange={(v) => patch("dedup", { auto_after_update: v })}- />- </SettingSection>-- <SettingSection- title={t("Merge footnotes")}- description={t(- "No-LLM consolidation: collapse duplicate ref rows into one footnote each, then renumber. Idempotent, safe to run any time.",- )}- >- <ToggleRow- label={t("Merge automatically after Update")}- value={settings.merge.auto_after_update}- onChange={(v) => patch("merge", { auto_after_update: v })}- />- <ToggleRow- label={t("Merge automatically after Audit")}- value={settings.merge.auto_after_audit}- onChange={(v) => patch("merge", { auto_after_audit: v })}- />- <ToggleRow- label={t("Merge automatically after Dedup")}- value={settings.merge.auto_after_dedup}- onChange={(v) => patch("merge", { auto_after_dedup: v })}- />- </SettingSection>-- <SettingSection- title={t("Chunking")}- description={t("Lower-level knobs that shape how content is split.")}- >- <NumberRow- label={t("Overlap ratio")}- help={t("Fraction of chunk size carried into the next chunk. 0–0.5.")}- value={settings.chunking.overlap_ratio}- onChange={(n) => patch("chunking", { overlap_ratio: n })}- min={0}- max={0.5}- step={0.05}- isFloat- />- <SelectRow- label={t("Boundary")}- help={t("Where the chunker prefers to cut.")}- value={settings.chunking.boundary}- options={[- { value: "paragraph", label: t("Paragraph") },- { value: "sentence", label: t("Sentence") },- ]}- onChange={(v) =>- patch("chunking", { boundary: v as "paragraph" | "sentence" })- }- />- <NumberRow- label={t("Min chunk chars")}- help={t("Floor for individual chunk size.")}- value={settings.chunking.min_chunk_chars}- onChange={(n) => patch("chunking", { min_chunk_chars: n })}- min={200}- max={64000}- step={100}- />- <NumberRow- label={t("Max chunk chars")}- help={t("Ceiling for individual chunk size.")}- value={settings.chunking.max_chunk_chars}- onChange={(n) => patch("chunking", { max_chunk_chars: n })}- min={200}- max={64000}- step={100}- />- </SettingSection>-- <SettingSection- title={t("References")}- description={t(- "How strictly facts must cite the chunk they were extracted from.",- )}- >- <ToggleRow- label={t("Require ref on every fact")}- help={t("Drops facts that come back without a ref.")}- value={settings.reference.enforce_required}- onChange={(v) => patch("reference", { enforce_required: v })}- />- <ToggleRow- label={t("Drop invalid refs (vs reject the whole fact)")}- help={t(- "On: keep the fact, drop only out-of-pool refs. Off: any bad ref rejects the fact.",- )}- value={settings.reference.drop_invalid_refs}- onChange={(v) => patch("reference", { drop_invalid_refs: v })}- />- </SettingSection>- </div>- );-}--// ── Field components ────────────────────────────────────────────────--interface NumberRowProps {- label: string;- help?: string;- value: number;- onChange: (n: number) => void;- min?: number;- max?: number;- step?: number;- isFloat?: boolean;-}--function NumberRow({- label,- help,- value,- onChange,- min,- max,- step = 1,- isFloat = false,-}: NumberRowProps) {- return (- <SettingRow- title={label}- description={help}- control={- <input- type="number"- value={value}- min={min}- max={max}- step={step}- onChange={(e) => {- const raw = e.target.value;- if (raw === "") return;- const n = isFloat ? parseFloat(raw) : parseInt(raw, 10);- if (!Number.isNaN(n)) onChange(n);- }}- className="w-24 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-right text-[12px] outline-none focus:border-[var(--primary)]"- />- }- />- );-}--interface ToggleRowProps {- label: string;- help?: string;- value: boolean;- onChange: (v: boolean) => void;-}--function ToggleRow({ label, help, value, onChange }: ToggleRowProps) {- return (- <SettingRow- title={label}- description={help}- control={- <button- type="button"- role="switch"- aria-checked={value}- onClick={() => onChange(!value)}- className={- "relative inline-flex h-5 w-9 items-center rounded-full transition " +- (value ? "bg-[var(--primary)]" : "bg-[var(--muted)]")- }- >- <span- className={- "inline-block h-4 w-4 transform rounded-full bg-white shadow transition " +- (value ? "translate-x-4" : "translate-x-0.5")- }- />- </button>- }- />- );-}--interface SelectRowProps {- label: string;- help?: string;- value: string;- options: { value: string; label: string }[];- onChange: (v: string) => void;-}--function SelectRow({ label, help, value, options, onChange }: SelectRowProps) {- return (- <SettingRow- title={label}- description={help}- control={- <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">- {options.map((o) => (- <button- key={o.value}- type="button"- onClick={() => onChange(o.value)}- className={- "rounded-md px-2.5 py-1 text-[12px] transition-all " +- (value === o.value- ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]")- }- >- {o.label}- </button>- ))}- </div>- }- />- );-}+export { default } from "@/features/settings/sections/MemorySettingsSection";diff --git a/web/app/(utility)/settings/models/page.tsx b/web/app/(utility)/settings/models/page.tsxindex e420bf6be..b429bb613 100644--- a/web/app/(utility)/settings/models/page.tsx+++ b/web/app/(utility)/settings/models/page.tsx@@ -1,37 +1 @@-"use client";--import { CategoryScroll } from "@/components/settings/CategoryScroll";--import ConnectionsSettingsPage from "../connections/page";-import LlmSettingsPage from "../llm/page";-import TaskModelsSettingsPage from "../task-models/page";-import EmbeddingSettingsPage from "../embedding/page";-import SearchSettingsPage from "../search/page";-import TtsSettingsPage from "../tts/page";-import SttSettingsPage from "../stt/page";-import ImageGenSettingsPage from "../image/page";-import VideoGenSettingsPage from "../video/page";--/**- * The Models category, in full: every service profile page stacked into one- * scroll instead of nine routes. `SettingsNav` links each leaf here as- * `#anchor` rather than a route change, so switching services never remounts- * this page — see `CategoryScroll`.- */-export default function ModelsSettingsPage() {- return (- <CategoryScroll- sections={[- { key: "connections", Component: ConnectionsSettingsPage },- { key: "llm", Component: LlmSettingsPage },- { key: "task-models", Component: TaskModelsSettingsPage },- { key: "embedding", Component: EmbeddingSettingsPage },- { key: "search", Component: SearchSettingsPage },- { key: "tts", Component: TtsSettingsPage },- { key: "stt", Component: SttSettingsPage },- { key: "imagegen", Component: ImageGenSettingsPage },- { key: "videogen", Component: VideoGenSettingsPage },- ]}- />- );-}+export { default } from "@/features/settings/sections/ModelsSettingsSection";diff --git a/web/app/(utility)/settings/network/page.tsx b/web/app/(utility)/settings/network/page.tsxindex e62989be8..ecbceb5c5 100644--- a/web/app/(utility)/settings/network/page.tsx+++ b/web/app/(utility)/settings/network/page.tsx@@ -1,523 +1 @@-"use client";--import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Loader2 } from "lucide-react";-import { useTranslation } from "react-i18next";--import {- SettingRow,- SettingSection,- SettingsPageHeader,- inputClass,-} from "@/components/settings/shared";-import { useSettings } from "@/components/settings/SettingsContext";-import {- DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,- MAX_CHAT_RESPONSE_TIMEOUT_SECONDS,- MIN_CHAT_RESPONSE_TIMEOUT_SECONDS,- clampChatResponseTimeout,- writeStoredChatResponseTimeout,-} from "@/context/app-shell-storage";-import { apiFetch, apiUrl } from "@/lib/api";-import {- RuntimeHealthCard,- TurnCoordinationSettings,- useRuntimeStatus,-} from "@/features/runtime-status";--type NetworkSettings = {- backend_port: number;- frontend_port: number;- public_api_base: string;- cors_origins: string[];-};--type NetworkSettingsPayload = {- settings: NetworkSettings;- effective: {- backend_url: string;- frontend_url: string;- browser_api_base: string;- api_base_source: string;- cors_mode: "explicit" | "permissive";- cors_origins: string[];- allow_remote_http_origins: boolean;- };- auth: {- enabled: boolean;- cookie_secure: boolean;- cookie_samesite: string;- cross_site_cookie_ready: boolean;- };- restart_required: boolean;-};--function splitOrigins(value: string): string[] {- return value- .split(/[,;\n]+/)- .map((item) => item.trim())- .filter(Boolean);-}--function normalizeDraft(payload: NetworkSettingsPayload): NetworkSettings {- return {- backend_port: payload.settings.backend_port,- frontend_port: payload.settings.frontend_port,- public_api_base: payload.settings.public_api_base || "",- cors_origins: payload.settings.cors_origins || [],- };-}--function DetailTile({- label,- value,- tone = "neutral",-}: {- label: string;- value: string;- tone?: "neutral" | "ok" | "warn";-}) {- const dot =- tone === "ok"- ? "bg-emerald-500"- : tone === "warn"- ? "bg-amber-500"- : "bg-[var(--border)]";- return (- <div className="rounded-xl border border-[var(--border)]/60 bg-[var(--card)] px-4 py-3">- <div className="flex items-center gap-2 text-[11px] font-medium text-[var(--muted-foreground)]">- <span className={`h-1.5 w-1.5 rounded-full ${dot}`} />- {label}- </div>- <div- className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]"- title={value}- >- {value || "-"}- </div>- </div>- );-}--/**- * Per-user chat idle-timeout control. Self-contained (its own fetch + save via- * the dedicated ``/settings/chat-response-timeout`` endpoint) and renders- * independently of the admin network settings below, so any user can adjust it.- * Mirrors the value to localStorage so the chat watchdog picks it up at once.- */-function ChatResponseTimeoutSection() {- const { t } = useTranslation();- const { registerExtension, pendingExtensionPayload, draftRevision } =- useSettings();- const [seconds, setSeconds] = useState<number>(- DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,- );- const [initial, setInitial] = useState<number>(- DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,- );- const [message, setMessage] = useState("");-- useEffect(() => {- let cancelled = false;- (async () => {- try {- const response = await apiFetch(apiUrl("/api/v1/settings"));- const data = (await response.json().catch(() => ({}))) as {- ui?: { chat_response_timeout?: number };- };- const value = clampChatResponseTimeout(- Number(data?.ui?.chat_response_timeout) ||- DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,- );- if (cancelled) return;- setSeconds(value);- setInitial(value);- writeStoredChatResponseTimeout(value);- } catch {- // keep the default- }- })();- return () => {- cancelled = true;- };- }, []);-- const dirty = seconds !== initial;-- // Flush through the global Apply (top toolbar) instead of a local button.- const secondsRef = useRef(seconds);- secondsRef.current = seconds;- const save = useCallback(async () => {- setMessage("");- try {- const value = clampChatResponseTimeout(secondsRef.current);- const response = await apiFetch(- apiUrl("/api/v1/settings/chat-response-timeout"),- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ chat_response_timeout: value }),- },- );- if (!response.ok) throw new Error(t("Failed to save."));- setSeconds(value);- setInitial(value);- writeStoredChatResponseTimeout(value);- } catch (err) {- setMessage(err instanceof Error ? err.message : String(err));- }- }, [t]);-- useEffect(() => {- registerExtension("chat-timeout", {- dirty,- save,- payload: { chat_response_timeout: seconds },- });- return () => registerExtension("chat-timeout", null);- }, [dirty, save, seconds, registerExtension]);-- return (- <SettingSection- title={t("Chat response timeout")}- description={t(- "How long chat waits for a reply before showing a timeout error. Increase it for slow tools like image or video generation.",- )}- >- <SettingRow- title={t("Timeout (seconds)")}- description={t(- "Between {{min}} and {{max}} seconds. Takes effect immediately — no restart.",- {- min: MIN_CHAT_RESPONSE_TIMEOUT_SECONDS,- max: MAX_CHAT_RESPONSE_TIMEOUT_SECONDS,- },- )}- control={- <input- className={`${inputClass} w-28`}- type="number"- min={MIN_CHAT_RESPONSE_TIMEOUT_SECONDS}- max={MAX_CHAT_RESPONSE_TIMEOUT_SECONDS}- value={seconds}- onChange={(event) => setSeconds(Number(event.target.value))}- />- }- />- {message && (- <p className="px-1 pb-3 text-[11.5px] text-[var(--muted-foreground)]">- {message}- </p>- )}- </SettingSection>- );-}--export default function NetworkSettingsPage() {- const { t } = useTranslation();- const runtime = useRuntimeStatus();- const { registerExtension, pendingExtensionPayload, draftRevision } =- useSettings();- const apiBasePlaceholder = "https://api.example.com";- const corsPlaceholder = "https://learn.example.com\nhttp://10.0.0.5:3782";- const [payload, setPayload] = useState<NetworkSettingsPayload | null>(null);- const [draft, setDraft] = useState<NetworkSettings | null>(null);- const [corsText, setCorsText] = useState("");- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- useEffect(() => {- let cancelled = false;- async function load() {- setLoading(true);- setError(null);- try {- const response = await apiFetch(apiUrl("/api/v1/settings/network"));- const data = (await response.json().catch(() => ({}))) as- | NetworkSettingsPayload- | { detail?: string };- if (!response.ok) {- throw new Error(- "detail" in data && data.detail- ? data.detail- : t("Failed to load network settings."),- );- }- if (cancelled) return;- const next = data as NetworkSettingsPayload;- setPayload(next);- const pending = pendingExtensionPayload("network") as- | NetworkSettings- | undefined;- const resolved = pending ?? normalizeDraft(next);- setDraft(resolved);- setCorsText((resolved.cors_origins || []).join("\n"));- } catch (err) {- if (!cancelled) {- setError(err instanceof Error ? err.message : String(err));- }- } finally {- if (!cancelled) setLoading(false);- }- }- load();- return () => {- cancelled = true;- };- }, [draftRevision, pendingExtensionPayload, t]);-- const dirty = useMemo(() => {- if (!payload || !draft) return false;- const current = normalizeDraft(payload);- return (- current.backend_port !== draft.backend_port ||- current.frontend_port !== draft.frontend_port ||- current.public_api_base !== draft.public_api_base ||- JSON.stringify(current.cors_origins) !==- JSON.stringify(splitOrigins(corsText))- );- }, [corsText, draft, payload]);-- // Flush through the global Apply (top toolbar) instead of a local button.- // Refs keep the registered ``save`` closure reading the latest draft.- const draftRef = useRef(draft);- draftRef.current = draft;- const corsRef = useRef(corsText);- corsRef.current = corsText;- const save = useCallback(async () => {- const current = draftRef.current;- if (!current) return;- setError(null);- try {- const response = await apiFetch(apiUrl("/api/v1/settings/network"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- ...current,- cors_origins: splitOrigins(corsRef.current),- }),- });- const data = (await response.json().catch(() => ({}))) as- | NetworkSettingsPayload- | { detail?: string };- if (!response.ok) {- throw new Error(- "detail" in data && data.detail- ? data.detail- : t("Failed to save network settings."),- );- }- const next = data as NetworkSettingsPayload;- setPayload(next);- setDraft(normalizeDraft(next));- setCorsText((next.settings.cors_origins || []).join("\n"));- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- }- }, [t]);-- useEffect(() => {- registerExtension("network", { dirty, save, payload: draft });- return () => registerExtension("network", null);- }, [dirty, draft, save, registerExtension]);-- return (- <div data-tour="tour-network">- <SettingsPageHeader- title={t("Network")}- description={t(- "Control the browser-facing API URL and CORS origins used by Docker, LAN, and reverse-proxy deployments.",- )}- />-- <p className="mb-7 text-[12px] text-[var(--muted-foreground)]">- {t("Network changes take effect after restart.")}- </p>-- <div className="mb-7">- <RuntimeHealthCard- snapshot={runtime}- onRefresh={runtime.refresh}- showDetails- />- {runtime.data ? (- <TurnCoordinationSettings- value={{- backendWorkers: runtime.data.workerCount,- coordinationMode: runtime.data.coordinationMode,- developmentReload: false,- leaseTtlSeconds: runtime.data.leaseTtlSeconds,- recoveryIntervalSeconds: runtime.data.recoveryIntervalSeconds,- }}- redisConfigured={runtime.data.redisConfigured}- />- ) : null}- </div>-- <ChatResponseTimeoutSection />-- {loading && (- <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">- <Loader2 className="h-4 w-4 animate-spin" />- {t("Loading network settings...")}- </div>- )}-- {!loading && error && (- <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">- {error}- </div>- )}-- {!loading && payload && draft && (- <>- <div className="mb-7 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">- <DetailTile- label={t("Browser API")}- value={payload.effective.browser_api_base}- tone="ok"- />- <DetailTile- label={t("CORS mode")}- value={- payload.effective.cors_mode === "permissive"- ? t("Permissive until auth is enabled")- : t("Explicit origins required")- }- tone={- payload.effective.cors_mode === "permissive" ? "ok" : "warn"- }- />- <DetailTile- label={t("Auth cookie")}- value={`${payload.auth.cookie_samesite}${- payload.auth.cookie_secure ? " + Secure" : ""- }`}- tone={- !payload.auth.enabled || payload.auth.cross_site_cookie_ready- ? "ok"- : "warn"- }- />- <DetailTile- label={t("Restart")}- value={t("Required after save")}- tone="warn"- />- </div>-- <SettingSection- title={t("Runtime ports")}- description={t(- "These ports are read during startup. Docker port mappings must match the container-side values.",- )}- >- <SettingRow- title={t("Backend port")}- description={t("FastAPI listens on this port.")}- control={- <input- className={`${inputClass} w-28`}- type="number"- min={1}- max={65535}- value={draft.backend_port}- onChange={(event) =>- setDraft((current) =>- current- ? {- ...current,- backend_port: Number(event.target.value),- }- : current,- )- }- />- }- />- <SettingRow- title={t("Frontend port")}- description={t("Next.js serves the Web UI on this port.")}- control={- <input- className={`${inputClass} w-28`}- type="number"- min={1}- max={65535}- value={draft.frontend_port}- onChange={(event) =>- setDraft((current) =>- current- ? {- ...current,- frontend_port: Number(event.target.value),- }- : current,- )- }- />- }- />- </SettingSection>-- <SettingSection- title={t("Browser API base")}- description={t(- "Set this when the browser cannot reach the backend through localhost, such as remote Docker or a reverse proxy.",- )}- >- <SettingRow- title={t("Public API base")}- description={t(- "Leave blank for local Docker. Use the externally reachable backend URL, including any proxy path.",- )}- control={- <input- className={`${inputClass} w-[360px] max-w-[48vw]`}- placeholder={apiBasePlaceholder}- value={draft.public_api_base}- onChange={(event) =>- setDraft((current) =>- current- ? { ...current, public_api_base: event.target.value }- : current,- )- }- />- }- />- </SettingSection>-- <SettingSection- title={t("CORS origins")}- description={t(- "Only required for authenticated cross-origin deployments. Use frontend origins, not API URLs.",- )}- >- <div className="py-4">- <textarea- className={`${inputClass} min-h-28 resize-y font-mono text-[12.5px] leading-relaxed`}- placeholder={corsPlaceholder}- value={corsText}- onChange={(event) => setCorsText(event.target.value)}- />- <p className="mt-2 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">- {t(- "Comma, semicolon, and newline separators are accepted. Bare host:port values are stored as http://host:port.",- )}- </p>- </div>- </SettingSection>-- {payload.auth.enabled && !payload.auth.cookie_secure && (- <div className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-[12.5px] leading-relaxed text-amber-700 dark:text-amber-300">- {t(- "Auth is enabled but secure cookies are off. Cross-site HTTPS deployments should set auth.cookie_secure=true and restart so SameSite=None cookies work in modern browsers.",- )}- </div>- )}- </>- )}- </div>- );-}+export { default } from "@/features/settings/sections/NetworkSettingsSection";diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsxindex 32c53f1af..e582fab5c 100644--- a/web/app/(utility)/settings/page.tsx+++ b/web/app/(utility)/settings/page.tsx@@ -3,14 +3,14 @@import { CategoryScroll } from "@/components/settings/CategoryScroll";import SettingsOverview from "@/components/settings/SettingsOverview";-import AboutSettingsPage from "./about/page";-import AgentsSettingsPage from "./agents/page";-import AppearanceSettingsPage from "./appearance/page";-import ChatSettingsPage from "./chat/page";-import DocumentParsingSettingsPage from "./document-parsing/page";-import MemorySettingsPage from "./memory/page";-import ModelsSettingsPage from "./models/page";-import NetworkSettingsPage from "./network/page";+import AboutSettingsPage from "@/features/settings/sections/AboutSettingsSection";+import AgentsSettingsPage from "@/features/settings/sections/AgentsSettingsSection";+import AppearanceSettingsPage from "@/features/settings/sections/AppearanceSettingsSection";+import ChatSettingsPage from "@/features/settings/sections/ChatSettingsSection";+import DocumentParsingSettingsPage from "@/features/settings/sections/DocumentParsingSettingsSection";+import MemorySettingsPage from "@/features/settings/sections/MemorySettingsSection";+import ModelsSettingsPage from "@/features/settings/sections/ModelsSettingsSection";+import NetworkSettingsPage from "@/features/settings/sections/NetworkSettingsSection";/*** Settings is one document: users can read it from Overview to About with adiff --git a/web/app/(utility)/settings/search/page.tsx b/web/app/(utility)/settings/search/page.tsxindex 87376856d..c213e67ad 100644--- a/web/app/(utility)/settings/search/page.tsx+++ b/web/app/(utility)/settings/search/page.tsx@@ -1,21 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";-import { SettingsPageHeader } from "@/components/settings/shared";--export default function SearchSettingsPage() {- const { t } = useTranslation();- return (- <div>- <SettingsPageHeader- title={t("Search")}- description={t(- "Configure web search providers. Used by the web_search tool and any agent step that hits the open web.",- )}- />- <ServiceConfigEditor service="search" />- </div>- );-}+export { default } from "@/features/settings/sections/models/SearchSettingsSection";diff --git a/web/app/(utility)/settings/starters/page.tsx b/web/app/(utility)/settings/starters/page.tsxindex 350115c1e..3876feac6 100644--- a/web/app/(utility)/settings/starters/page.tsx+++ b/web/app/(utility)/settings/starters/page.tsx@@ -1,193 +1 @@-"use client";--import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import Link from "next/link";-import { ArrowUpRight, Loader2 } from "lucide-react";-import { useTranslation } from "react-i18next";--import {- SettingRow,- SettingSection,- SettingsPageHeader,- inputClass,-} from "@/components/settings/shared";-import { useSettings } from "@/components/settings/SettingsContext";-import { apiFetch, apiUrl } from "@/lib/api";-import { EXTENSION_ENDPOINTS } from "@/lib/settings-extensions";--type StarterSettings = { trace_count: number };--type StarterSettingsPayload = {- settings: StarterSettings;- bounds: { trace_count: [number, number] };-};--export default function StarterSettingsPage() {- const { t } = useTranslation();- const { registerExtension, pendingExtensionPayload, draftRevision } =- useSettings();- const [payload, setPayload] = useState<StarterSettingsPayload | null>(null);- const [draft, setDraft] = useState<StarterSettings | null>(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- useEffect(() => {- let cancelled = false;- async function load() {- setLoading(true);- setError(null);- try {- const response = await apiFetch(- apiUrl(EXTENSION_ENDPOINTS["chat-starters"]),- );- const data = (await response.json().catch(() => ({}))) as- | StarterSettingsPayload- | { detail?: string };- if (!response.ok) {- throw new Error(- "detail" in data && data.detail- ? String(data.detail)- : t("Failed to load starter settings."),- );- }- if (cancelled) return;- const next = data as StarterSettingsPayload;- setPayload(next);- // An edit left behind earlier in this session (or parked in a saved- // draft) wins over the server value — leaving the page is not a way- // to discard changes.- const pending = pendingExtensionPayload("chat-starters") as- | StarterSettings- | undefined;- setDraft(pending ? { ...pending } : { ...next.settings });- } catch (err) {- if (!cancelled)- setError(err instanceof Error ? err.message : String(err));- } finally {- if (!cancelled) setLoading(false);- }- }- load();- return () => {- cancelled = true;- };- }, [draftRevision, pendingExtensionPayload, t]);-- const dirty = useMemo(- () =>- Boolean(- payload && draft && payload.settings.trace_count !== draft.trace_count,- ),- [draft, payload],- );-- // Flush through the global Apply (top toolbar) instead of a local button.- const draftRef = useRef(draft);- draftRef.current = draft;- const save = useCallback(async () => {- const current = draftRef.current;- if (!current) return;- setError(null);- try {- const response = await apiFetch(- apiUrl(EXTENSION_ENDPOINTS["chat-starters"]),- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(current),- },- );- const data = (await response.json().catch(() => ({}))) as- | StarterSettingsPayload- | { detail?: string };- if (!response.ok) {- throw new Error(- "detail" in data && data.detail- ? String(data.detail)- : t("Failed to save starter settings."),- );- }- const next = data as StarterSettingsPayload;- setPayload(next);- setDraft({ ...next.settings });- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- }- }, [t]);-- useEffect(() => {- registerExtension("chat-starters", { dirty, save, payload: draft });- return () => registerExtension("chat-starters", null);- }, [dirty, draft, save, registerExtension]);-- const bounds = payload?.bounds.trace_count;-- return (- <div>- <SettingsPageHeader- title={t("Starting points")}- description={t(- "The three lines under the composer on an empty home screen, generated from your long-term memory and what you have been working on lately.",- )}- />-- {loading && (- <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">- <Loader2 className="h-4 w-4 animate-spin" />- {t("Loading starter settings...")}- </div>- )}-- {!loading && error && (- <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">- {error}- </div>- )}-- {!loading && payload && draft && (- <SettingSection- title={t("Material")}- description={t(- "Your consolidated memory is always included. This controls how much raw recent activity goes with it — conversations, practice questions, searches, documents, in one list ordered by time.",- )}- >- <SettingRow- title={t("Recent activities")}- description={t(- "More gives the model a longer view of what you have touched; fewer keeps it focused on this week. Takes effect the next time the lines are regenerated.",- )}- control={- <input- className={`${inputClass} w-28`}- type="number"- min={bounds?.[0] ?? 3}- max={bounds?.[1] ?? 100}- value={draft.trace_count}- onChange={(event) =>- setDraft((current) =>- current- ? { ...current, trace_count: Number(event.target.value) }- : current,- )- }- />- }- />- </SettingSection>- )}-- {!loading && payload && (- <p className="mt-5 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">- {t("These lines are written by the active model unless you pin one.")}{" "}- <Link- href="/settings/models#task-models"- className="inline-flex items-center gap-1 text-[var(--foreground)] underline-offset-2 hover:underline"- >- {t("Task models")}- <ArrowUpRight className="h-3 w-3" />- </Link>- </p>- )}- </div>- );-}+export { default } from "@/features/settings/sections/StartersSettingsSection";diff --git a/web/app/(utility)/settings/stt/page.tsx b/web/app/(utility)/settings/stt/page.tsxindex 3db2f250b..53f384ac2 100644--- a/web/app/(utility)/settings/stt/page.tsx+++ b/web/app/(utility)/settings/stt/page.tsx@@ -1,21 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";-import { SettingsPageHeader } from "@/components/settings/shared";--export default function SttSettingsPage() {- const { t } = useTranslation();- return (- <div>- <SettingsPageHeader- title={t("Speech-to-Text")}- description={t(- "Transcribe the chat composer's microphone recordings. Works with any OpenAI-compatible audio API — OpenAI, Groq, SiliconFlow, Azure, or a local server.",- )}- />- <ServiceConfigEditor service="stt" />- </div>- );-}+export { default } from "@/features/settings/sections/models/SttSettingsSection";diff --git a/web/app/(utility)/settings/task-models/page.tsx b/web/app/(utility)/settings/task-models/page.tsxindex cb7b5f304..0535cd6c7 100644--- a/web/app/(utility)/settings/task-models/page.tsx+++ b/web/app/(utility)/settings/task-models/page.tsx@@ -1,21 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { TaskModelsEditor } from "@/components/settings/TaskModelsEditor";-import { SettingsPageHeader } from "@/components/settings/shared";--export default function TaskModelsSettingsPage() {- const { t } = useTranslation();- return (- <div>- <SettingsPageHeader- title={t("Task models")}- description={t(- "Conversation titles and home screen starting points. Configured like the LLM — pick a provider, then a model. Left empty, both use the LLM.",- )}- />- <TaskModelsEditor />- </div>- );-}+export { default } from "@/features/settings/sections/models/TaskModelsSettingsSection";diff --git a/web/app/(utility)/settings/tools/page.tsx b/web/app/(utility)/settings/tools/page.tsxindex 458a2e995..4ee02be1d 100644--- a/web/app/(utility)/settings/tools/page.tsx+++ b/web/app/(utility)/settings/tools/page.tsx@@ -1,611 +1 @@-"use client";--import { useCallback, useEffect, useMemo, useState } from "react";-import { ChevronDown, Loader2, Lock, Search, Wrench, X } from "lucide-react";-import Link from "next/link";-import { useTranslation } from "react-i18next";--import { useSettings } from "@/components/settings/SettingsContext";-import { SettingsPageHeader } from "@/components/settings/shared";-import { apiFetch, apiUrl } from "@/lib/api";-import { invalidateEnabledOptionalToolsCache } from "@/lib/tools-settings";-import {- toolAvailabilityCopy,- toolEffectiveEnabled,-} from "@/lib/tool-availability";--type ToolParameter = {- name: string;- type: string;- description: string;- required: boolean;- default: unknown;- enum: string[] | null;-};--type ToolHints = {- short_description: string;- when_to_use: string;- input_format: string;- guideline: string;- note: string;- phase: string;- aliases: { name: string; description: string; phase: string }[];-};--type BuiltinTool = {- name: string;- description: string;- parameters: ToolParameter[];- hints: { en: ToolHints; zh: ToolHints };- aliases: string[];- toggleable: boolean;- enabled: boolean;- // ``coming_soon`` tools are listed for visibility but the chat agent- // cannot invoke them. The settings UI surfaces them with a locked-off- // toggle and a "Coming soon" badge.- coming_soon?: boolean;- // The capability that owns this tool (e.g. "solve" / "mastery"), or null- // for a plain system built-in. Owned tools render in their own section- // below the built-in tools.- capability?: string | null;- // Runtime readiness is independent of the saved composer preference.- available?: boolean;- unavailable_reason?: string | null;-};--type ToolsResponse = {- tools: BuiltinTool[];- enabled_optional_tools: string[];-};--type ToolSection = {- key: string;- label: string;- hint: string;- tools: BuiltinTool[];-};--// Display labels for capability-owned tool sections, keyed by the backend's-// capability id. Falls back to the raw id for any unmapped capability.-const CAPABILITY_LABELS: Record<string, { zh: string; en: string }> = {- solve: { zh: "深度解题", en: "Deep Solve" },- mastery: { zh: "精通路径", en: "Mastery Path" },-};--export default function ToolsSettingsPage() {- const { t } = useTranslation();- const { language } = useSettings();- const [tools, setTools] = useState<BuiltinTool[] | null>(null);- const [error, setError] = useState<string | null>(null);- const [expanded, setExpanded] = useState<Set<string>>(new Set());- const [enabled, setEnabled] = useState<Set<string>>(new Set());- const [pending, setPending] = useState<Set<string>>(new Set());- const [saveError, setSaveError] = useState<string | null>(null);- const [query, setQuery] = useState("");-- useEffect(() => {- let cancelled = false;- (async () => {- try {- const res = await apiFetch(apiUrl("/api/v1/tools"));- if (!res.ok) throw new Error(`HTTP ${res.status}`);- const payload = (await res.json()) as ToolsResponse;- if (!cancelled) {- setTools(payload.tools);- setEnabled(new Set(payload.enabled_optional_tools ?? []));- }- } catch (err) {- if (!cancelled) {- setError(err instanceof Error ? err.message : String(err));- }- }- })();- return () => {- cancelled = true;- };- }, []);-- const persist = useCallback(async (next: Set<string>) => {- const body = JSON.stringify({ enabled_tools: Array.from(next) });- const res = await apiFetch(apiUrl("/api/v1/settings/enabled-tools"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body,- });- if (!res.ok) throw new Error(`HTTP ${res.status}`);- const payload = (await res.json()) as { enabled_optional_tools: string[] };- // Bust the cached snapshot any other page in this tab is holding.- invalidateEnabledOptionalToolsCache();- return new Set(payload.enabled_optional_tools);- }, []);-- const handleToggleEnabled = useCallback(- async (toolName: string) => {- if (pending.has(toolName)) return;- const before = enabled;- const next = new Set(before);- if (next.has(toolName)) next.delete(toolName);- else next.add(toolName);- setEnabled(next);- setPending((prev) => new Set(prev).add(toolName));- setSaveError(null);- try {- const saved = await persist(next);- setEnabled(saved);- } catch (err) {- setEnabled(before);- setSaveError(err instanceof Error ? err.message : String(err));- } finally {- setPending((prev) => {- const out = new Set(prev);- out.delete(toolName);- return out;- });- }- },- [enabled, pending, persist],- );-- const sections = useMemo<ToolSection[] | null>(() => {- if (!tools) return null;- const zh = language === "zh";- // Buckets: toggleable (体验增强) first, then locked-on built-ins, then one- // section per capability for its owned tools. Backend order is preserved- // within each bucket (mirrors USER_TOGGLEABLE_TOOL_NAMES / the- // BUILTIN_TOOL_TYPES registration order). Coming-soon tools share the- // toggleable bucket — same concept, just temporarily unavailable.- const experience: BuiltinTool[] = [];- const builtin: BuiltinTool[] = [];- const capabilities = new Map<string, BuiltinTool[]>();- for (const tool of tools) {- if (tool.capability) {- const list = capabilities.get(tool.capability) ?? [];- list.push(tool);- capabilities.set(tool.capability, list);- } else if (tool.coming_soon) {- experience.push(tool);- } else {- (tool.toggleable ? experience : builtin).push(tool);- }- }- const out: ToolSection[] = [];- if (experience.length) {- out.push({- key: "experience",- label: zh ? "体验增强" : "Experience Enhancement",- hint: zh- ? "用户可选;按需为 chat agent 开启或关闭。"- : "User-toggleable. Switch on or off to shape the chat agent's behavior.",- tools: experience,- });- }- if (builtin.length) {- out.push({- key: "builtin",- label: zh ? "内置工具" : "Built-in Tools",- hint: zh- ? "Chat agent 在需要时自动挂载,无需手动开关。"- : "Mounted automatically by the chat agent when needed. Not user-toggleable.",- tools: builtin,- });- }- for (const [cap, list] of capabilities) {- const label = CAPABILITY_LABELS[cap]?.[zh ? "zh" : "en"] ?? cap;- out.push({- key: `cap:${cap}`,- label: zh ? `${label} · 能力工具` : `${label} · Capability Tools`,- hint: zh- ? "该能力的专属工具,仅在此能力运行时挂载。"- : "Tools specific to this capability; mounted only when it runs.",- tools: list,- });- }- return out;- }, [tools, language]);-- const filteredSections = useMemo<ToolSection[] | null>(() => {- if (!sections) return null;- const needle = query.trim().toLocaleLowerCase();- if (!needle) return sections;-- return sections- .map((section) => ({- ...section,- tools: section.tools.filter((tool) => {- const hints = tool.hints[language];- const alternateHints = tool.hints[language === "zh" ? "en" : "zh"];- const searchableText = [- tool.name,- tool.description,- ...tool.aliases,- hints.short_description,- hints.when_to_use,- hints.input_format,- hints.guideline,- hints.note,- ...hints.aliases.flatMap((alias) => [- alias.name,- alias.description,- alias.phase,- ]),- alternateHints.short_description,- alternateHints.when_to_use,- alternateHints.input_format,- alternateHints.guideline,- alternateHints.note,- ...tool.parameters.flatMap((parameter) => [- parameter.name,- parameter.type,- parameter.description,- ...(parameter.enum ?? []),- ]),- ]- .filter(Boolean)- .join(" ")- .toLocaleLowerCase();- return searchableText.includes(needle);- }),- }))- .filter((section) => section.tools.length > 0);- }, [language, query, sections]);-- const toggleExpanded = (name: string) => {- setExpanded((prev) => {- const next = new Set(prev);- if (next.has(name)) next.delete(name);- else next.add(name);- return next;- });- };-- return (- <div data-tour="tour-tools">- <SettingsPageHeader- title={t("Tools")}- description={t(- "Switch user-toggleable tools on or off. Locked tools are mounted automatically when the chat agent needs them.",- )}- />-- <div className="mb-8">- <label className="sr-only" htmlFor="tools-search">- {t("Search tools")}- </label>- <div className="relative">- <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />- <input- id="tools-search"- value={query}- onChange={(event) => setQuery(event.target.value)}- placeholder={t("Search tools")}- aria-label={t("Search tools")}- className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-10 pr-10 text-[13px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)]/60 focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/20"- spellCheck={false}- />- {query && (- <button- type="button"- onClick={() => setQuery("")}- aria-label={t("Clear")}- title={t("Clear")}- className="absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)] focus:outline-none focus:ring-2 focus:ring-[var(--ring)]/30"- >- <X className="h-3.5 w-3.5" />- </button>- )}- </div>- </div>-- {error && (- <div className="rounded-xl border border-red-500/40 bg-red-500/5 px-4 py-3 text-[12px] text-red-500">- {t("Failed to load tools")}: {error}- </div>- )}-- {saveError && (- <div className="mb-4 rounded-xl border border-red-500/40 bg-red-500/5 px-4 py-3 text-[12px] text-red-500">- {t("Failed to save")}: {saveError}- </div>- )}-- {!tools && !error && (- <div className="flex items-center gap-2 text-[12px] text-[var(--muted-foreground)]">- <Loader2 className="h-3.5 w-3.5 animate-spin" />- {t("Loading...")}- </div>- )}-- {filteredSections && query.trim() && filteredSections.length === 0 && (- <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-8 text-center text-[12.5px] text-[var(--muted-foreground)]">- {t('No tools match “{{query}}”.', { query: query.trim() })}- </div>- )}-- {filteredSections && filteredSections.length > 0 && (- <div className="space-y-8">- {filteredSections.map((section) => {- const list = section.tools;- if (list.length === 0) return null;- return (- <section key={section.key}>- <header className="mb-3 flex items-baseline justify-between gap-3">- <div className="min-w-0">- <h2 className="text-[14px] font-semibold tracking-tight text-[var(--foreground)]">- {section.label}- </h2>- <p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">- {section.hint}- </p>- </div>- <span className="shrink-0 text-[11px] text-[var(--muted-foreground)]">- {list.length}- </span>- </header>- <div className="border-t border-[var(--border)]/60">- {list.map((tool, idx) => {- const isOpen = expanded.has(tool.name);- const hints = tool.hints[language];- const isPending = pending.has(tool.name);- const isComingSoon = !!tool.coming_soon;- const isAvailable = tool.available !== false;- const availability = !isAvailable- ? toolAvailabilityCopy(- tool.unavailable_reason,- language === "zh" ? "zh" : "en",- )- : null;- const isEnabled = toolEffectiveEnabled(- tool.toggleable ? enabled.has(tool.name) : true,- isAvailable,- isComingSoon,- );- return (- <div- key={tool.name}- className={- idx > 0- ? "border-t border-[var(--border)]/50"- : undefined- }- >- <div className="flex w-full items-start gap-3 px-5 py-4">- <Wrench- className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${- isComingSoon || !isAvailable- ? "text-[var(--muted-foreground)]/40"- : "text-[var(--muted-foreground)]"- }`}- />- <button- type="button"- onClick={() => toggleExpanded(tool.name)}- className="flex min-w-0 flex-1 items-start gap-3 text-left"- aria-expanded={isOpen}- >- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <span- className={`font-mono text-[13px] font-medium ${- isComingSoon- ? "text-[var(--foreground)]/60"- : "text-[var(--foreground)]"- }`}- >- {tool.name}- </span>- {tool.aliases.length > 0 && (- <span className="text-[10.5px] text-[var(--muted-foreground)]/70">- {tool.aliases.join(" · ")}- </span>- )}- {isComingSoon && (- <span className="inline-flex items-center gap-1 rounded-full border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">- {language === "zh"- ? "敬请期待"- : "Coming soon"}- </span>- )}- {availability && !isComingSoon && (- <span className="inline-flex items-center rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300">- {availability.badge}- </span>- )}- </div>- <p- className={`mt-1 text-[12.5px] leading-relaxed ${- isComingSoon- ? "text-[var(--muted-foreground)]/70"- : "text-[var(--muted-foreground)]"- }`}- >- {hints.short_description || tool.description}- </p>- {availability && !isComingSoon && (- <p className="mt-1 text-[11.5px] leading-relaxed text-amber-700 dark:text-amber-300">- {availability.detail}{" "}- {availability.href && (- <Link- href={availability.href}- className="font-medium underline underline-offset-2"- >- {language === "zh" ? "打开设置" : "Open settings"}- </Link>- )}- </p>- )}- </div>- <ChevronDown- className={`mt-1 h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition-transform ${- isOpen ? "rotate-180" : ""- }`}- />- </button>- <div className="mt-0.5 flex shrink-0 items-center gap-2">- {isComingSoon ? (- <ToolToggle- checked={false}- disabled- onChange={() => {- /* locked */- }}- label={- language === "zh" ? "敬请期待" : "Coming soon"- }- />- ) : !isAvailable ? (- <ToolToggle- checked={false}- disabled- onChange={() => {- /* runtime unavailable */- }}- label={availability?.badge ?? t("Not configured")}- />- ) : tool.toggleable ? (- <ToolToggle- checked={isEnabled}- disabled={isPending}- onChange={() => handleToggleEnabled(tool.name)}- label={t(isEnabled ? "On" : "Off")}- />- ) : (- <span- className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)]/40 px-2 py-0.5 text-[10.5px] text-[var(--muted-foreground)]"- title={t(- "Auto-mounted by the agent when needed. Not user-toggleable.",- )}- >- <Lock className="h-3 w-3" />- {t("Always on")}- </span>- )}- </div>- </div>- {isOpen && (- <div className="space-y-4 border-t border-[var(--border)]/40 bg-[var(--background)]/40 px-5 py-4 text-[12.5px] leading-relaxed">- {hints.when_to_use && (- <Field- label={t("When to use")}- body={hints.when_to_use}- />- )}- {hints.input_format && (- <Field- label={t("Input format")}- body={hints.input_format}- mono- />- )}- {hints.guideline && (- <Field- label={t("Guideline")}- body={hints.guideline}- />- )}- {hints.note && (- <Field label={t("Note")} body={hints.note} />- )}- {tool.parameters.length > 0 && (- <div>- <div className="mb-1 text-[10.5px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]/80">- {t("Parameters")}- </div>- <ul className="space-y-1.5">- {tool.parameters.map((p) => (- <li- key={p.name}- className="flex items-baseline gap-2"- >- <span className="font-mono text-[12px] text-[var(--foreground)]">- {p.name}- </span>- <span className="text-[10.5px] text-[var(--muted-foreground)]/70">- {p.type}- {p.required- ? ""- : ` · ${t("optional")}`}- </span>- {p.description && (- <span className="text-[12px] text-[var(--muted-foreground)]">- — {p.description}- </span>- )}- </li>- ))}- </ul>- </div>- )}- </div>- )}- </div>- );- })}- </div>- </section>- );- })}- </div>- )}- </div>- );-}--function ToolToggle({- checked,- disabled,- onChange,- label,-}: {- checked: boolean;- disabled: boolean;- onChange: () => void;- label: string;-}) {- return (- <button- type="button"- role="switch"- aria-checked={checked}- aria-label={label}- disabled={disabled}- onClick={onChange}- className={`relative inline-flex h-[18px] w-[32px] shrink-0 items-center rounded-full border transition-colors ${- checked- ? "border-[var(--primary)] bg-[var(--primary)]/70"- : "border-[var(--border)] bg-[var(--muted)]/50"- } ${disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer"}`}- >- <span- className={`inline-block h-[12px] w-[12px] transform rounded-full bg-white shadow transition-transform ${- checked ? "translate-x-[16px]" : "translate-x-[2px]"- }`}- />- </button>- );-}--function Field({- label,- body,- mono,-}: {- label: string;- body: string;- mono?: boolean;-}) {- return (- <div>- <div className="mb-1 text-[10.5px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]/80">- {label}- </div>- <p- className={`whitespace-pre-wrap text-[12.5px] leading-relaxed text-[var(--foreground)]/90 ${- mono ? "font-mono" : ""- }`}- >- {body}- </p>- </div>- );-}+export { default } from "@/features/settings/sections/ToolsSettingsSection";diff --git a/web/app/(utility)/settings/tts/page.tsx b/web/app/(utility)/settings/tts/page.tsxindex 454f9d4d6..c86eaf6e5 100644--- a/web/app/(utility)/settings/tts/page.tsx+++ b/web/app/(utility)/settings/tts/page.tsx@@ -1,71 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";-import { SettingsPageHeader } from "@/components/settings/shared";-import { useVoiceAutoplayPreference } from "@/hooks/useVoiceAutoplay";--function AutoplayToggle() {- const { t } = useTranslation();- const { value, setValue, loading } = useVoiceAutoplayPreference();- return (- <div className="flex items-start justify-between gap-6 border-y border-[var(--border)]/50 py-3.5">- <div className="min-w-0 flex-1">- <div className="text-[13.5px] font-medium text-[var(--foreground)]">- {t("Auto-play replies")}- </div>- <p className="mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">- {t(- "Read each assistant reply aloud automatically. You can also toggle this per conversation from the speaker button.",- )}- </p>- </div>- <button- type="button"- role="switch"- aria-checked={value}- disabled={loading}- onClick={() => setValue(!value)}- className={`relative mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors disabled:opacity-50 ${- value ? "bg-[var(--foreground)]" : "bg-[var(--border)]"- }`}- aria-label={t("Auto-play replies")}- >- <span- className={`inline-block h-4 w-4 transform rounded-full bg-[var(--background)] shadow-sm transition-transform ${- value ? "translate-x-4" : "translate-x-0.5"- }`}- />- </button>- </div>- );-}--export default function TtsSettingsPage() {- const { t } = useTranslation();- return (- <div className="space-y-10">- <SettingsPageHeader- title={t("Text-to-Speech")}- description={t(- "Read assistant replies aloud from the chat speaker button. Works with any OpenAI-compatible audio API — OpenAI, OpenRouter, Groq, SiliconFlow, Azure, or a local server.",- )}- />-- <ServiceConfigEditor service="tts" />-- <section>- <div className="mb-3">- <h2 className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">- {t("Playback")}- </h2>- <p className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">- {t("How spoken replies behave in chat.")}- </p>- </div>- <AutoplayToggle />- </section>- </div>- );-}+export { default } from "@/features/settings/sections/models/TtsSettingsSection";diff --git a/web/app/(utility)/settings/video-learning/page.tsx b/web/app/(utility)/settings/video-learning/page.tsxindex 21ed01e12..35d0b60cb 100644--- a/web/app/(utility)/settings/video-learning/page.tsx+++ b/web/app/(utility)/settings/video-learning/page.tsx@@ -1,235 +1 @@-"use client";--import { useEffect, useState } from "react";-import { CheckCircle2, Loader2, Save, Server, Youtube } from "lucide-react";-import { useTranslation } from "react-i18next";--import { SettingsPageHeader } from "@/components/settings/shared";-import {- getVideoLearningSettings,- saveVideoLearningSettings,- testInvidious,- type VideoLearningSettings,-} from "@/lib/video-learning-api";--const DEFAULTS: VideoLearningSettings = {- version: 1,- default_provider: "youtube",- youtube: { transcript_provider: "youtube_transcript_api" },- invidious: { api_base_url: "", public_base_url: "" },-};--export default function VideoLearningSettingsPage() {- const { t } = useTranslation();- const [settings, setSettings] = useState(DEFAULTS);- const [loading, setLoading] = useState(true);- const [saving, setSaving] = useState(false);- const [message, setMessage] = useState("");-- useEffect(() => {- void getVideoLearningSettings()- .then(setSettings)- .catch((error) =>- setMessage(- error instanceof Error- ? error.message- : t("Settings could not be loaded."),- ),- )- .finally(() => setLoading(false));- }, [t]);-- const save = async () => {- setSaving(true);- setMessage("");- try {- setSettings(await saveVideoLearningSettings(settings));- setMessage(- t("Saved. New and reopened videos use this provider immediately."),- );- } catch (error) {- setMessage(- error instanceof Error- ? error.message- : t("Settings could not be saved."),- );- } finally {- setSaving(false);- }- };-- const test = async () => {- setMessage(t("Testing Invidious…"));- try {- const result = await testInvidious(settings);- setMessage(- result.ok- ? t("Invidious connected ({{message}}).", result)- : t("Invidious unavailable: {{message}}", result),- );- } catch (error) {- setMessage(- error instanceof Error ? error.message : t("Connection test failed."),- );- }- };-- return (- <div className="space-y-6">- <SettingsPageHeader- title={t("Video Learning")}- description={t(- "Choose native YouTube or a self-hosted Invidious instance. Provider changes do not rebuild learning materials or reset progress.",- )}- />- {loading ? (- <Loader2 className="h-5 w-5 animate-spin" />- ) : (- <>- <div className="grid gap-3 sm:grid-cols-2">- {(- [- [- "youtube",- Youtube,- t(- "Official privacy-enhanced IFrame Player. No media is proxied or stored.",- ),- ],- [- "invidious",- Server,- t(- "HTML5 playback through your configured Invidious instance.",- ),- ],- ] as const- ).map(([provider, Icon, description]) => (- <button- key={provider}- type="button"- onClick={() =>- setSettings((current) => ({- ...current,- default_provider: provider,- }))- }- className={`rounded-xl border p-4 text-left ${settings.default_provider === provider ? "border-[var(--primary)] ring-1 ring-[var(--primary)]" : "border-[var(--border)]"}`}- >- <div className="flex items-center gap-2 font-medium">- <Icon className="h-5 w-5" />- {provider === "youtube"- ? t("Native YouTube")- : t("Self-hosted Invidious")}- </div>- <p className="mt-2 text-sm text-[var(--muted-foreground)]">- {description}- </p>- </button>- ))}- </div>-- <div className="space-y-4 rounded-xl border border-[var(--border)] p-5">- <h3 className="font-medium">{t("Invidious connection")}</h3>- <label className="block text-sm">- <span className="mb-1 block">{t("Backend API origin")}</span>- <input- value={settings.invidious.api_base_url}- onChange={(event) =>- setSettings((current) => ({- ...current,- invidious: {- ...current.invidious,- api_base_url: event.target.value,- },- }))- }- placeholder={t("Invidious API URL")}- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono"- />- </label>- <label className="block text-sm">- <span className="mb-1 block">- {t("Browser-facing origin (optional)")}- </span>- <input- value={settings.invidious.public_base_url}- onChange={(event) =>- setSettings((current) => ({- ...current,- invidious: {- ...current.invidious,- public_base_url: event.target.value,- },- }))- }- placeholder={t("Defaults to the API origin")}- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono"- />- </label>- <button- type="button"- onClick={() => void test()}- className="rounded-lg border border-[var(--border)] px-3 py-2 text-sm"- >- {t("Test connection")}- </button>- </div>-- <label className="flex items-center justify-between gap-4 rounded-xl border border-[var(--border)] p-4 text-sm">- <span>- <strong>{t("YouTube transcript adapter")}</strong>- <br />- <span className="text-[var(--muted-foreground)]">- {t(- "Optional captions; playback remains available when the package or captions are unavailable.",- )}- </span>- </span>- <select- value={settings.youtube.transcript_provider}- onChange={(event) =>- setSettings((current) => ({- ...current,- youtube: {- transcript_provider: event.target.value as- | "youtube_transcript_api"- | "none",- },- }))- }- className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-2"- >- <option value="youtube_transcript_api">- {t("youtube-transcript-api")}- </option>- <option value="none">{t("Disabled")}</option>- </select>- </label>-- <div className="flex items-center gap-3">- <button- type="button"- onClick={() => void save()}- disabled={saving}- className="inline-flex items-center gap-2 rounded-lg bg-[var(--foreground)] px-4 py-2 text-sm text-[var(--background)] disabled:opacity-50"- >- {saving ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Save className="h-4 w-4" />- )}{" "}- {t("Save")}- </button>- {message && (- <p className="inline-flex items-center gap-1 text-sm text-[var(--muted-foreground)]">- <CheckCircle2 className="h-4 w-4" />- {message}- </p>- )}- </div>- </>- )}- </div>- );-}+export { default } from "@/features/settings/sections/VideoLearningSettingsSection";diff --git a/web/app/(utility)/settings/video/page.tsx b/web/app/(utility)/settings/video/page.tsxindex 6fd2ca136..133a7010c 100644--- a/web/app/(utility)/settings/video/page.tsx+++ b/web/app/(utility)/settings/video/page.tsx@@ -1,21 +1 @@-"use client";--import { useTranslation } from "react-i18next";--import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";-import { SettingsPageHeader } from "@/components/settings/shared";--export default function VideoGenSettingsPage() {- const { t } = useTranslation();- return (- <div>- <SettingsPageHeader- title={t("Video Generation")}- description={t(- "Text-to-video model used by the chat 'videogen' tool. Rendering is asynchronous and may take a minute or more. Uses async task providers like Volcengine Seedance.",- )}- />- <ServiceConfigEditor service="videogen" />- </div>- );-}+export { default } from "@/features/settings/sections/models/VideoSettingsSection";diff --git a/web/components/settings/CategoryScroll.tsx b/web/components/settings/CategoryScroll.tsxindex c7b65767e..d64e872ae 100644--- a/web/components/settings/CategoryScroll.tsx+++ b/web/components/settings/CategoryScroll.tsx@@ -2,7 +2,7 @@import { useEffect, useRef } from "react";-import { useSettings } from "./SettingsContext";+import { useSettings } from "@/features/settings/store/SettingsStore";export type CategorySection = {key: string;diff --git a/web/components/settings/CodexOAuthCard.tsx b/web/components/settings/CodexOAuthCard.tsxindex f785a13b7..06557f747 100644--- a/web/components/settings/CodexOAuthCard.tsx+++ b/web/components/settings/CodexOAuthCard.tsx@@ -26,7 +26,7 @@ import {type CodexReasoningModel,} from "@/lib/codex-oauth";-import { useSettings } from "./SettingsContext";+import { useSettings } from "@/features/settings/store/SettingsStore";export function CodexOAuthCard() {const { t } = useTranslation();diff --git a/web/components/settings/ConnectionsEditor.tsx b/web/components/settings/ConnectionsEditor.tsxindex 98e8e2436..dcaf32244 100644--- a/web/components/settings/ConnectionsEditor.tsx+++ b/web/components/settings/ConnectionsEditor.tsx@@ -23,7 +23,7 @@ import {type ConnectionTarget,type ServiceName,useSettings,-} from "./SettingsContext";+} from "@/features/settings/store/SettingsStore";import { inputClass, selectClass, selectOptionClass } from "./shared";/**diff --git a/web/components/settings/DimensionField.tsx b/web/components/settings/DimensionField.tsxindex c15cb6969..79dbbd50e 100644--- a/web/components/settings/DimensionField.tsx+++ b/web/components/settings/DimensionField.tsx@@ -3,7 +3,7 @@import { useState } from "react";import { useTranslation } from "react-i18next";-import type { CatalogModel, EmbeddingCapabilities } from "./SettingsContext";+import type { CatalogModel, EmbeddingCapabilities } from "@/features/settings/store/SettingsStore";import { nativeSelectClass, selectOptionClass } from "./shared";const CUSTOM_DIM_SENTINEL = "__custom__";diff --git a/web/components/settings/ModelCards.tsx b/web/components/settings/ModelCards.tsxindex 2df4e5de9..ad922ebee 100644--- a/web/components/settings/ModelCards.tsx+++ b/web/components/settings/ModelCards.tsx@@ -8,7 +8,7 @@ import type {CatalogModel,CatalogProfile,ServiceName,-} from "./SettingsContext";+} from "@/features/settings/store/SettingsStore";/*** The two levels of a model settings page, as cards.diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsxindex aec8f1aba..2d58d3e9a 100644--- a/web/components/settings/ServiceConfigEditor.tsx+++ b/web/components/settings/ServiceConfigEditor.tsx@@ -42,7 +42,7 @@ import {getActiveModel,getActiveProfile,useSettings,-} from "./SettingsContext";+} from "@/features/settings/store/SettingsStore";import { DimensionField } from "./DimensionField";import {AddCard,diff --git a/web/components/settings/SettingsLoadStatusBanner.tsx b/web/components/settings/SettingsLoadStatusBanner.tsxindex ddceda8e7..09ed82715 100644--- a/web/components/settings/SettingsLoadStatusBanner.tsx+++ b/web/components/settings/SettingsLoadStatusBanner.tsx@@ -4,7 +4,7 @@ import { useState } from "react";import { AlertTriangle, Loader2, RefreshCw } from "lucide-react";import { useTranslation } from "react-i18next";-import { useSettings } from "./SettingsContext";+import { useSettings } from "@/features/settings/store/SettingsStore";// Surface the result of the initial /api/v1/settings + /api/v1/system/status// load so Docker / first-run users know *why* the page is empty when thediff --git a/web/components/settings/SettingsNav.tsx b/web/components/settings/SettingsNav.tsxindex c205ec1ce..2328ecf39 100644--- a/web/components/settings/SettingsNav.tsx+++ b/web/components/settings/SettingsNav.tsx@@ -21,7 +21,7 @@ import {type Lang,type SettingsLeaf,} from "@/lib/settings-nav";-import { serviceReadiness, useSettings } from "./SettingsContext";+import { serviceReadiness, useSettings } from "@/features/settings/store/SettingsStore";/*** Same-page anchor vs. a real route change. A merged category's childrendiff --git a/web/components/settings/SettingsOverview.tsx b/web/components/settings/SettingsOverview.tsxindex 00bb4a7a3..e70a02821 100644--- a/web/components/settings/SettingsOverview.tsx+++ b/web/components/settings/SettingsOverview.tsx@@ -21,7 +21,7 @@ import {serviceReadiness,useSettings,type ServiceReadiness,-} from "./SettingsContext";+} from "@/features/settings/store/SettingsStore";/*** The settings landing page.diff --git a/web/components/settings/SettingsStatusPanel.tsx b/web/components/settings/SettingsStatusPanel.tsxindex 603e5cedd..329afd0b6 100644--- a/web/components/settings/SettingsStatusPanel.tsx+++ b/web/components/settings/SettingsStatusPanel.tsx@@ -3,7 +3,7 @@import { useTranslation } from "react-i18next";import MemoryUsageItem from "@/components/settings/MemoryUsageItem";-import { useSettings } from "@/components/settings/SettingsContext";+import { useSettings } from "@/features/settings/store/SettingsStore";import { statusDotClass } from "@/components/settings/shared";import {RuntimeHealthCard,diff --git a/web/components/settings/SettingsToolbar.tsx b/web/components/settings/SettingsToolbar.tsxindex b967a4df6..62c82201a 100644--- a/web/components/settings/SettingsToolbar.tsx+++ b/web/components/settings/SettingsToolbar.tsx@@ -5,7 +5,7 @@ import { usePathname } from "next/navigation";import { useTranslation } from "react-i18next";import { storagePathFor } from "@/lib/settings-nav";-import { useSettings } from "./SettingsContext";+import { useSettings } from "@/features/settings/store/SettingsStore";/*** Sticky toolbar above the sub-page content.diff --git a/web/components/settings/SettingsTourOverlay.tsx b/web/components/settings/SettingsTourOverlay.tsxindex 005e2ed77..79068b9f1 100644--- a/web/components/settings/SettingsTourOverlay.tsx+++ b/web/components/settings/SettingsTourOverlay.tsx@@ -5,7 +5,7 @@ import { usePathname } from "next/navigation";import { ChevronLeft, ChevronRight, Sparkles, X } from "lucide-react";import { useTranslation } from "react-i18next";-import { TOUR_STEPS, useSettings } from "./SettingsContext";+import { TOUR_STEPS, useSettings } from "@/features/settings/store/SettingsStore";// Cross-route guided tour. Mounted in the settings layout so the same// instance survives navigation between sub-pages. After each stepdiff --git a/web/components/settings/TaskModelsEditor.tsx b/web/components/settings/TaskModelsEditor.tsxindex f790070d7..e793bb3a0 100644--- a/web/components/settings/TaskModelsEditor.tsx+++ b/web/components/settings/TaskModelsEditor.tsx@@ -11,7 +11,7 @@ import {getActiveModel,getActiveProfile,useSettings,-} from "./SettingsContext";+} from "@/features/settings/store/SettingsStore";import { selectClass, selectOptionClass } from "./shared";/**diff --git a/web/components/settings/ThemePreviewCard.tsx b/web/components/settings/ThemePreviewCard.tsxindex 81e0a0db6..8e325e52a 100644--- a/web/components/settings/ThemePreviewCard.tsx+++ b/web/components/settings/ThemePreviewCard.tsx@@ -2,7 +2,7 @@import { Check } from "lucide-react";-import type { UiSettings } from "./SettingsContext";+import type { UiSettings } from "@/features/settings/store/SettingsStore";type Theme = UiSettings["theme"];diff --git a/web/components/settings/codex-profile.ts b/web/components/settings/codex-profile.tsindex 5c382004c..7d148d730 100644--- a/web/components/settings/codex-profile.ts+++ b/web/components/settings/codex-profile.ts@@ -2,7 +2,7 @@ import type {CatalogProfile,ProviderOption,ServiceName,-} from "./SettingsContext";+} from "@/features/settings/store/SettingsStore";/** The tag the backend stamps on the profile its Codex OAuth service owns. */export const CODEX_MANAGED_BY = "openai_codex_oauth";diff --git a/web/components/settings/search-providers.ts b/web/components/settings/search-providers.tsindex 982662a51..ef5c1d5df 100644--- a/web/components/settings/search-providers.ts+++ b/web/components/settings/search-providers.ts@@ -11,7 +11,7 @@// entry), every field is shown: better an extra control than a hidden one the// provider actually needs.-import type { ProviderOption } from "./SettingsContext";+import type { ProviderOption } from "@/features/settings/store/SettingsStore";export type SearchProviderFieldSpec = {/** Provider authenticates with an API key. */diff --git a/web/components/settings/shared.tsx b/web/components/settings/shared.tsxindex 58c0db105..9479f5ebf 100644--- a/web/components/settings/shared.tsx+++ b/web/components/settings/shared.tsx@@ -1,6 +1,6 @@"use client";-import type { CatalogProfile, ServiceName } from "./SettingsContext";+import type { CatalogProfile, ServiceName } from "@/features/settings/store/SettingsStore";export const fieldControlClass ="w-full rounded-lg border border-[var(--border)] px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)]";diff --git a/web/features/settings/sections/AboutSettingsSection.tsx b/web/features/settings/sections/AboutSettingsSection.tsxnew file mode 100644index 000000000..d67d9d680--- /dev/null+++ b/web/features/settings/sections/AboutSettingsSection.tsx@@ -0,0 +1,480 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import {+ ArrowUpRight,+ Check,+ CircleAlert,+ Download,+ Github,+ RefreshCw,+ RotateCw,+ ShieldCheck,+} from "lucide-react";+import { useTranslation } from "react-i18next";++import { Toggle } from "@/components/settings/Toggle";+import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+} from "@/components/settings/shared";+import { ConfirmDialog } from "@/components/ui/ConfirmDialog";+import Button from "@/components/ui/Button";+import {+ checkAppUpdate,+ fetchAppUpdateJob,+ fetchAppUpdateStatus,+ requestAppUpdate,+ setAppUpdateChecks,+ updateJobIsActive,+ type AppUpdateStatus,+ type InstallMode,+ type UpdateJob,+ type UpdateJobStatus,+} from "@/lib/app-update";+import { normalizeVersionTag } from "@/lib/version";++const POLL_INTERVAL_MS = 800;+const POLL_TIMEOUT_MS = 120_000;++const INSTALLATION_LABELS: Record<InstallMode, string> = {+ pypi: "PyPI package",+ source: "Source checkout",+ docker: "Docker container",+ unknown: "Unknown installation",+};++function jobTone(status: UpdateJobStatus) {+ if (status === "failed") return "text-red-600 dark:text-red-400";+ if (status === "succeeded") return "text-emerald-700 dark:text-emerald-400";+ return "text-sky-700 dark:text-sky-400";+}++export default function AboutSettingsPage() {+ const { t, i18n } = useTranslation();+ const [status, setStatus] = useState<AppUpdateStatus | null>(null);+ const [job, setJob] = useState<UpdateJob | null>(null);+ const [loading, setLoading] = useState(true);+ const [checking, setChecking] = useState(false);+ const [savingChecks, setSavingChecks] = useState(false);+ const [requesting, setRequesting] = useState(false);+ const [confirmOpen, setConfirmOpen] = useState(false);+ const [error, setError] = useState("");++ const load = useCallback(async () => {+ try {+ const next = await fetchAppUpdateStatus();+ setStatus(next);+ setJob(next.job);+ setError(next.check_error || "");+ } catch (cause) {+ setError(+ cause instanceof Error+ ? cause.message+ : (t("Unable to load version information.") as string),+ );+ } finally {+ setLoading(false);+ }+ }, [t]);++ useEffect(() => {+ void load();+ }, [load]);++ const activeJob = Boolean(job && updateJobIsActive(job.status));+ useEffect(() => {+ if (!activeJob) return;+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = Date.now() + POLL_TIMEOUT_MS;++ const poll = async () => {+ try {+ const next = await fetchAppUpdateJob();+ if (cancelled) return;+ if (next) {+ setJob(next);+ if (!updateJobIsActive(next.status)) {+ if (next.status === "succeeded") await load();+ return;+ }+ }+ } catch {+ // The backend is expected to disappear while the launcher updates and+ // restarts it. Keep polling until it reconnects or the deadline passes.+ }+ if (cancelled) return;+ if (Date.now() >= deadline) {+ setError(t("DeepTutor did not reconnect before the update timeout."));+ return;+ }+ timer = setTimeout(poll, POLL_INTERVAL_MS);+ };++ void poll();+ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ };+ }, [activeJob, load, t]);++ const check = useCallback(async () => {+ setChecking(true);+ setError("");+ try {+ const next = await checkAppUpdate();+ setStatus(next);+ setJob(next.job);+ } catch (cause) {+ setError(+ cause instanceof Error+ ? cause.message+ : (t("Unable to check for updates.") as string),+ );+ } finally {+ setChecking(false);+ }+ }, [t]);++ const changeChecks = useCallback(+ async (enabled: boolean) => {+ setSavingChecks(true);+ setError("");+ try {+ const next = await setAppUpdateChecks(enabled);+ setStatus(next);+ setJob(next.job);+ } catch (cause) {+ setError(+ cause instanceof Error+ ? cause.message+ : (t("Unable to save update settings.") as string),+ );+ } finally {+ setSavingChecks(false);+ }+ },+ [t],+ );++ const update = useCallback(async () => {+ setRequesting(true);+ setError("");+ try {+ const next = await requestAppUpdate();+ setJob(next);+ setConfirmOpen(false);+ } catch (cause) {+ setError(+ cause instanceof Error+ ? cause.message+ : (t("Unable to start the update.") as string),+ );+ } finally {+ setRequesting(false);+ }+ }, [t]);++ const currentVersion =+ normalizeVersionTag(status?.current_version) ??+ normalizeVersionTag(process.env.NEXT_PUBLIC_APP_VERSION) ??+ "—";+ const latestVersion = normalizeVersionTag(status?.release?.version);+ const checkedAt = useMemo(() => {+ if (!status?.checked_at) return "";+ const parsed = new Date(status.checked_at);+ if (Number.isNaN(parsed.getTime())) return "";+ return parsed.toLocaleString(+ i18n.language?.toLowerCase().startsWith("zh") ? "zh-CN" : "en-US",+ { dateStyle: "medium", timeStyle: "short" },+ );+ }, [i18n.language, status?.checked_at]);++ const installMode = status?.installation.mode ?? "unknown";+ const canUpdate = Boolean(+ status?.is_admin &&+ status.check_enabled &&+ status.update_available &&+ status.installation.automatic_update &&+ status.launcher_managed &&+ !activeJob,+ );+ const upToDate = Boolean(status?.release && !status.update_available);++ return (+ <div data-tour="tour-about" className="pb-8">+ <SettingsPageHeader+ title={t("About")}+ description={t(+ "DeepTutor version, release channel, and the safest update path for this installation.",+ )}+ />++ <section className="relative mb-10 overflow-hidden border-y border-[var(--border)]/60 py-7">+ <div+ aria-hidden+ className="pointer-events-none absolute -right-12 -top-16 h-40 w-40 rounded-full border-[28px] border-[var(--foreground)]/[0.025]"+ />+ <div className="relative flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">+ <div>+ <div className="mb-2 flex items-center gap-2 text-[11px] font-medium uppercase tracking-[0.16em] text-[var(--muted-foreground)]">+ <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />+ {t("Running version")}+ </div>+ <div className="font-serif text-[38px] font-semibold leading-none tracking-[-0.035em] text-[var(--foreground)]">+ {currentVersion}+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {status?.release?.url && (+ <a+ href={status.release.url}+ target="_blank"+ rel="noreferrer noopener"+ className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--accent)] hover:text-[var(--foreground)]"+ >+ {t("Release notes")}+ <ArrowUpRight className="h-3.5 w-3.5" />+ </a>+ )}+ {status?.is_admin && (+ <Button+ type="button"+ size="sm"+ variant="secondary"+ loading={checking}+ disabled={!status.check_enabled || activeJob}+ icon={<RefreshCw className="h-3.5 w-3.5" />}+ onClick={() => void check()}+ >+ {t("Check now")}+ </Button>+ )}+ {canUpdate && (+ <Button+ type="button"+ size="sm"+ icon={<Download className="h-3.5 w-3.5" />}+ onClick={() => setConfirmOpen(true)}+ >+ {t("Update to {{version}}", { version: latestVersion ?? "" })}+ </Button>+ )}+ </div>+ </div>+ </section>++ {error && (+ <div className="mb-7 flex items-start gap-2 border-l-2 border-red-500/70 py-1 pl-3 text-[12.5px] leading-relaxed text-red-600 dark:text-red-400">+ <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />+ <span>{error}</span>+ </div>+ )}++ <SettingSection title={t("Software")}>+ <SettingRow+ title={t("Current version")}+ control={<CodeValue value={currentVersion} />}+ />+ <SettingRow+ title={t("Installation")}+ description={t(+ status?.installation.reason || "How DeepTutor is installed here.",+ )}+ control={+ <span className="text-[12.5px] text-[var(--foreground)]">+ {t(INSTALLATION_LABELS[installMode])}+ </span>+ }+ />+ <SettingRow+ title={t("Release channel")}+ description={t(+ "Only stable, published DeepTutor releases are considered.",+ )}+ control={+ <span className="text-[12.5px] text-[var(--foreground)]">+ {t("Stable")}+ </span>+ }+ />+ </SettingSection>++ <SettingSection+ title={t("Updates")}+ description={t(+ "Version checks are cached for 24 hours. DeepTutor never installs an update without confirmation.",+ )}+ >+ <SettingRow+ title={t("Check for updates")}+ description={t(+ "Turn this off for offline or controlled deployments.",+ )}+ control={+ status?.is_admin ? (+ <Toggle+ checked={status?.check_enabled ?? true}+ disabled={loading || savingChecks || activeJob}+ onChange={(enabled) => void changeChecks(enabled)}+ />+ ) : (+ <span className="text-[12.5px] text-[var(--muted-foreground)]">+ {status?.check_enabled ? t("On") : t("Off")}+ </span>+ )+ }+ />+ <SettingRow+ title={t("Latest stable release")}+ description={+ checkedAt+ ? t("Last checked {{time}}", { time: checkedAt })+ : status?.check_enabled+ ? t("Not checked yet")+ : t("Version checks are disabled.")+ }+ control={+ <div className="flex items-center gap-2">+ {upToDate && <Check className="h-3.5 w-3.5 text-emerald-500" />}+ <CodeValue value={latestVersion ?? "—"} />+ </div>+ }+ />++ {status?.release?.migration_warning && (+ <div className="flex items-start gap-2 border-t border-[var(--border)]/50 py-3.5 text-[12.5px] leading-relaxed text-amber-700 dark:text-amber-400">+ <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />+ {t(+ "This release mentions migrations or breaking changes. Read the release notes before updating.",+ )}+ </div>+ )}++ {status?.release?.excerpt && (+ <div className="border-t border-[var(--border)]/50 py-4">+ <div className="mb-2 text-[11px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">+ {status.release.name || t("What changed")}+ </div>+ <p className="max-w-2xl whitespace-pre-line text-[12.5px] leading-6 text-[var(--muted-foreground)]">+ {status.release.excerpt}+ </p>+ </div>+ )}++ {status && !status.installation.automatic_update && (+ <div className="border-t border-[var(--border)]/50 py-4">+ <div className="mb-2 flex items-center gap-2 text-[12.5px] font-medium text-[var(--foreground)]">+ <ShieldCheck className="h-4 w-4 text-[var(--muted-foreground)]" />+ {t("Managed by your installation")}+ </div>+ <p className="mb-3 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(status.installation.reason)}+ </p>+ <code className="block overflow-x-auto rounded-lg bg-[var(--accent)]/60 px-3 py-2 text-[11.5px] text-[var(--foreground)]">+ {status.installation.command}+ </code>+ </div>+ )}++ {job && (+ <div+ className="border-t border-[var(--border)]/50 py-4"+ aria-live="polite"+ >+ <div+ className={`flex items-center gap-2 text-[12.5px] font-medium ${jobTone(job.status)}`}+ >+ {updateJobIsActive(job.status) ? (+ <RotateCw className="h-3.5 w-3.5 animate-spin" />+ ) : job.status === "succeeded" ? (+ <Check className="h-3.5 w-3.5" />+ ) : (+ <CircleAlert className="h-3.5 w-3.5" />+ )}+ {t(`updateJob.${job.status}`)}+ </div>+ {job.error && (+ <p className="mt-2 text-[12px] text-red-600 dark:text-red-400">+ {job.error}+ </p>+ )}+ </div>+ )}+ </SettingSection>++ <SettingSection title={t("Project")}>+ <ResourceRow+ title={t("GitHub")}+ description={t("Source code, issues, and contributions")}+ href="https://github.com/HKUDS/DeepTutor"+ icon={<Github className="h-4 w-4" />}+ />+ <ResourceRow+ title={t("Documentation")}+ description={t("Installation, configuration, and guides")}+ href="https://docs.deeptutor.info"+ icon={<ArrowUpRight className="h-4 w-4" />}+ />+ </SettingSection>++ <ConfirmDialog+ open={confirmOpen}+ title={t("Update and restart DeepTutor?")}+ confirmLabel={t("Update and restart")}+ busy={requesting}+ busyLabel={t("Preparing update…")}+ onConfirm={() => void update()}+ onCancel={() => setConfirmOpen(false)}+ >+ {t(+ "DeepTutor will briefly stop, install {{version}}, and reopen with the same settings. Active conversations must finish first.",+ { version: latestVersion ?? "" },+ )}+ </ConfirmDialog>+ </div>+ );+}++function CodeValue({ value }: { value: string }) {+ return (+ <code className="rounded-md bg-[var(--accent)]/60 px-2 py-1 text-[11.5px] tabular-nums text-[var(--foreground)]">+ {value}+ </code>+ );+}++function ResourceRow({+ title,+ description,+ href,+ icon,+}: {+ title: string;+ description: string;+ href: string;+ icon: React.ReactNode;+}) {+ return (+ <a+ href={href}+ target="_blank"+ rel="noreferrer noopener"+ className="group flex items-center justify-between gap-5 border-t border-[var(--border)]/50 py-3.5 first:border-t-0"+ >+ <div>+ <div className="text-[13.5px] font-medium text-[var(--foreground)]">+ {title}+ </div>+ <p className="mt-1 text-[12px] text-[var(--muted-foreground)]">+ {description}+ </p>+ </div>+ <span className="text-[var(--muted-foreground)] transition-transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5 group-hover:text-[var(--foreground)]">+ {icon}+ </span>+ </a>+ );+}diff --git a/web/features/settings/sections/AgentsSettingsSection.tsx b/web/features/settings/sections/AgentsSettingsSection.tsxnew file mode 100644index 000000000..2a5f4dd60--- /dev/null+++ b/web/features/settings/sections/AgentsSettingsSection.tsx@@ -0,0 +1,42 @@+"use client";++import { CategoryScroll } from "@/components/settings/CategoryScroll";+import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";++const ClaudeCodeAgentSettingsPage = () => <SubagentSettingsEditor kind="claude_code" />;+const CodexAgentSettingsPage = () => <SubagentSettingsEditor kind="codex" />;+const AntigravityAgentSettingsPage = () => <SubagentSettingsEditor kind="antigravity" />;+const KimiAgentSettingsPage = () => <SubagentSettingsEditor kind="kimi" />;+const OpencodeAgentSettingsPage = () => <SubagentSettingsEditor kind="opencode" />;+const MimoAgentSettingsPage = () => <SubagentSettingsEditor kind="mimo" />;+const HermesAgentSettingsPage = () => <SubagentSettingsEditor kind="hermes" />;+const OpenClawAgentSettingsPage = () => <SubagentSettingsEditor kind="openclaw" />;+const DeepSeekHarnessAgentSettingsPage = () => (+ <SubagentSettingsEditor kind="deepseek_harness" />+);++/**+ * The Partners & Agents category, in full — see `ModelsSettingsPage` for the+ * pattern. All leaves persist to the same `subagent.json`, so this remains one+ * shared draft behind the individual routes.+ */+export default function AgentsSettingsPage() {+ return (+ <CategoryScroll+ sections={[+ { key: "agent-claude-code", Component: ClaudeCodeAgentSettingsPage },+ { key: "agent-codex", Component: CodexAgentSettingsPage },+ { key: "agent-antigravity", Component: AntigravityAgentSettingsPage },+ { key: "agent-kimi", Component: KimiAgentSettingsPage },+ { key: "agent-opencode", Component: OpencodeAgentSettingsPage },+ { key: "agent-mimo", Component: MimoAgentSettingsPage },+ { key: "agent-hermes", Component: HermesAgentSettingsPage },+ { key: "agent-openclaw", Component: OpenClawAgentSettingsPage },+ {+ key: "agent-deepseek-harness",+ Component: DeepSeekHarnessAgentSettingsPage,+ },+ ]}+ />+ );+}diff --git a/web/features/settings/sections/AppearanceSettingsSection.tsx b/web/features/settings/sections/AppearanceSettingsSection.tsxnew file mode 100644index 000000000..8050dee61--- /dev/null+++ b/web/features/settings/sections/AppearanceSettingsSection.tsx@@ -0,0 +1,241 @@+"use client";++import dynamic from "next/dynamic";+import { useTranslation } from "react-i18next";++import type { CodeBlockThemeId } from "@/components/common/code-block-themes";+import { CODE_BLOCK_THEME_OPTIONS } from "@/components/common/code-block-themes";+import { Toggle } from "@/components/settings/Toggle";+import { useUiSettings } from "@/features/settings/store";+import { ThemePreviewCard } from "@/components/settings/ThemePreviewCard";+import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+ selectClass,+ selectOptionClass,+} from "@/components/settings/shared";++const CODE_BLOCK_PREVIEW_SNIPPET = `def fibonacci(n):+ """Generate the first n Fibonacci numbers."""+ a, b = 0, 1+ result = []+ for _ in range(n):+ result.append(a)+ a, b = b, a + b+ return result+++# Build a deliberately long summary so the wrapping preference is easy to see+summary = f"First twenty Fibonacci values rendered with the selected syntax theme, line-number setting, and wrapping preference: {', '.join(str(value) for value in fibonacci(20))}"+print(summary)+`;++const RichCodeBlockPreview = dynamic(+ () => import("@/components/common/RichCodeBlock"),+ { ssr: false },+);++export default function AppearanceSettingsPage() {+ const { t } = useTranslation();+ const {+ theme,+ language,+ responseLanguage,+ codeBlockTheme,+ codeBlockShowLineNumbers,+ codeBlockWrapLongLines,+ updateTheme,+ updateLanguage,+ updateResponseLanguage,+ updateCodeBlockTheme,+ updateCodeBlockShowLineNumbers,+ updateCodeBlockWrapLongLines,+ } = useUiSettings();++ // All code-block values come straight from the settings context (backed by+ // AppShellContext, the single source of truth), so the toggles reflect the+ // current preference without any local mirror state.+ const handleShowLineNumbersChange = (next: boolean) => {+ void updateCodeBlockShowLineNumbers(next);+ };++ const handleWrapLongLinesChange = (next: boolean) => {+ void updateCodeBlockWrapLongLines(next);+ };++ return (+ <div data-tour="tour-appearance">+ <SettingsPageHeader+ title={t("Appearance")}+ description={t(+ "Tune the visual theme and interface language. Changes apply immediately and are stored in your account.",+ )}+ />++ <SettingSection+ title={t("Language")}+ description={t("Choose the interface language.")}+ >+ <SettingRow+ title={t("Interface language")}+ description={t(+ "Controls navigation, settings, and status text only.",+ )}+ control={+ <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">+ {(["en", "zh"] as const).map((v) => (+ <button+ key={v}+ onClick={() => updateLanguage(v)}+ className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${+ language === v+ ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {v === "en" ? t("language.english") : t("language.chinese")}+ </button>+ ))}+ </div>+ }+ />+ <SettingRow+ title={t("Model output language")}+ description={t(+ "Sets the default language for chat and capability responses.",+ )}+ control={+ <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">+ {(["en", "zh"] as const).map((value) => (+ <button+ key={value}+ onClick={() => updateResponseLanguage(value)}+ className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${+ responseLanguage === value+ ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {value === "en"+ ? t("language.english")+ : t("language.chinese")}+ </button>+ ))}+ </div>+ }+ />+ </SettingSection>++ <SettingSection+ title={t("Theme")}+ description={t(+ "Pick the colour palette and interface style. Each tile previews the theme it applies.",+ )}+ >+ <div className="py-3.5">+ {/* Order is intentional: Default (pure-white neutral, the default+ selection; theme id "snow" kept for stored preferences) →+ warm-light Cream → warm-dark Dark → cool-dark Glass. */}+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ {(+ [+ { id: "snow", label: t("Default") },+ { id: "light", label: t("Cream") },+ { id: "dark", label: t("Dark") },+ { id: "glass", label: t("Glass") },+ ] as const+ ).map(({ id, label }) => (+ <ThemePreviewCard+ key={id}+ theme={id}+ label={label}+ selected={theme === id}+ onSelect={updateTheme}+ />+ ))}+ </div>+ <p className="mt-4 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]/80">+ {t(+ "Default is a clean pure-white theme with a blue accent. Cream is warm and paper-like with a terracotta accent. Dark keeps Cream's warmth on near-black. Glass adds translucent purple panels on a deep gradient.",+ )}+ </p>+ </div>+ </SettingSection>++ <SettingSection+ title={t("Code blocks")}+ description={t(+ "Choose how code snippets look across the app. Changes apply immediately to saved and streamed responses.",+ )}+ >+ <div className="border-t border-[var(--border)]/50 py-3.5 first:border-t-0">+ <div className="text-[13.5px] font-medium text-[var(--foreground)]">+ {t("Preview")}+ </div>+ <p className="mb-3 mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t("Updates live as you change the settings below.")}+ </p>+ <RichCodeBlockPreview+ raw={CODE_BLOCK_PREVIEW_SNIPPET}+ lang="python"+ />+ </div>++ <SettingRow+ title={t("Syntax theme")}+ description={t(+ "Select the Prism theme used for highlighted code blocks.",+ )}+ control={+ <select+ value={codeBlockTheme}+ onChange={(event) =>+ void updateCodeBlockTheme(+ event.target.value as CodeBlockThemeId,+ )+ }+ className={`${selectClass} min-w-[220px] pr-8`}+ >+ {CODE_BLOCK_THEME_OPTIONS.map((option) => (+ <option+ key={option.id}+ value={option.id}+ className={selectOptionClass}+ >+ {option.label}+ </option>+ ))}+ </select>+ }+ />++ <SettingRow+ title={t("Show line numbers")}+ description={t(+ "Display a gutter with line numbers beside each code block.",+ )}+ control={+ <Toggle+ checked={codeBlockShowLineNumbers}+ onChange={handleShowLineNumbersChange}+ />+ }+ />++ <SettingRow+ title={t("Wrap long lines")}+ description={t(+ "Wrap long code lines instead of forcing horizontal scrolling.",+ )}+ control={+ <Toggle+ checked={codeBlockWrapLongLines}+ onChange={handleWrapLongLinesChange}+ />+ }+ />+ </SettingSection>+ </div>+ );+}diff --git a/web/features/settings/sections/AttachmentsSettingsSection.tsx b/web/features/settings/sections/AttachmentsSettingsSection.tsxnew file mode 100644index 000000000..2ffb1954f--- /dev/null+++ b/web/features/settings/sections/AttachmentsSettingsSection.tsx@@ -0,0 +1,274 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";++import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+ inputClass,+} from "@/components/settings/shared";+import { useSettings } from "@/features/settings/store/SettingsStore";+import { apiFetch, apiUrl } from "@/lib/api";+import { EXTENSION_ENDPOINTS } from "@/lib/settings-extensions";++type AttachmentSettings = {+ max_file_mb: number;+ max_total_mb: number;+ max_chars_per_doc: number;+ max_chars_total: number;+};++type AttachmentSettingsPayload = {+ settings: AttachmentSettings;+ effective: {+ max_file_bytes: number;+ max_total_bytes: number;+ max_chars_per_doc: number;+ max_chars_total: number;+ ws_max_size: number;+ };+ bounds: {+ max_file_mb: [number, number];+ max_total_mb: [number, number];+ chars: [number, number];+ };+ restart_required_for_larger_uploads: boolean;+};++function normalizeDraft(+ payload: AttachmentSettingsPayload,+): AttachmentSettings {+ return { ...payload.settings };+}++export default function AttachmentSettingsPage() {+ const { t } = useTranslation();+ const { registerExtension, pendingExtensionPayload, draftRevision } =+ useSettings();+ const [payload, setPayload] = useState<AttachmentSettingsPayload | null>(+ null,+ );+ const [draft, setDraft] = useState<AttachmentSettings | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ async function load() {+ setLoading(true);+ setError(null);+ try {+ const response = await apiFetch(+ apiUrl(EXTENSION_ENDPOINTS["chat-attachments"]),+ );+ const data = (await response.json().catch(() => ({}))) as+ | AttachmentSettingsPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in data && data.detail+ ? data.detail+ : t("Failed to load attachment settings."),+ );+ }+ if (cancelled) return;+ const next = data as AttachmentSettingsPayload;+ setPayload(next);+ const pending = pendingExtensionPayload("chat-attachments") as+ | AttachmentSettings+ | undefined;+ setDraft(pending ?? normalizeDraft(next));+ } catch (err) {+ if (!cancelled) {+ setError(err instanceof Error ? err.message : String(err));+ }+ } finally {+ if (!cancelled) setLoading(false);+ }+ }+ load();+ return () => {+ cancelled = true;+ };+ }, [draftRevision, pendingExtensionPayload, t]);++ const dirty = useMemo(() => {+ if (!payload || !draft) return false;+ const current = normalizeDraft(payload);+ return (+ current.max_file_mb !== draft.max_file_mb ||+ current.max_total_mb !== draft.max_total_mb ||+ current.max_chars_per_doc !== draft.max_chars_per_doc ||+ current.max_chars_total !== draft.max_chars_total+ );+ }, [draft, payload]);++ // Flush through the global Apply (top toolbar) instead of a local button.+ const draftRef = useRef(draft);+ draftRef.current = draft;+ const save = useCallback(async () => {+ const current = draftRef.current;+ if (!current) return;+ setError(null);+ try {+ const response = await apiFetch(+ apiUrl(EXTENSION_ENDPOINTS["chat-attachments"]),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(current),+ },+ );+ const data = (await response.json().catch(() => ({}))) as+ | AttachmentSettingsPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in data && data.detail+ ? String(data.detail)+ : t("Failed to save attachment settings."),+ );+ }+ const next = data as AttachmentSettingsPayload;+ setPayload(next);+ setDraft(normalizeDraft(next));+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ }, [t]);++ useEffect(() => {+ registerExtension("chat-attachments", { dirty, save, payload: draft });+ return () => registerExtension("chat-attachments", null);+ }, [dirty, draft, save, registerExtension]);++ const setField = (field: keyof AttachmentSettings) => (value: number) =>+ setDraft((current) => (current ? { ...current, [field]: value } : current));++ const bounds = payload?.bounds;++ return (+ <div>+ <SettingsPageHeader+ title={t("Attachments")}+ description={t(+ "Upload caps and extraction budgets for files attached in chat — shared by the main chat, books, quiz follow-ups, and partners.",+ )}+ />++ {loading && (+ <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ {t("Loading attachment settings...")}+ </div>+ )}++ {!loading && error && (+ <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">+ {error}+ </div>+ )}++ {!loading && payload && draft && (+ <>+ <SettingSection+ title={t("Size limits")}+ description={t(+ "Caps are enforced when a file is picked and again server-side on every message. Lower limits apply immediately; raising them needs a backend restart so larger uploads fit through the WebSocket transport.",+ )}+ >+ <SettingRow+ title={t("Max file size (MB)")}+ description={t("Largest single file the composer accepts.")}+ control={+ <input+ className={`${inputClass} w-28`}+ type="number"+ min={bounds?.max_file_mb[0] ?? 1}+ max={bounds?.max_file_mb[1] ?? 1024}+ value={draft.max_file_mb}+ onChange={(event) =>+ setField("max_file_mb")(Number(event.target.value))+ }+ />+ }+ />+ <SettingRow+ title={t("Max total per message (MB)")}+ description={t(+ "Combined size of all attachments on a single message. Never below the per-file cap.",+ )}+ control={+ <input+ className={`${inputClass} w-28`}+ type="number"+ min={bounds?.max_total_mb[0] ?? 1}+ max={bounds?.max_total_mb[1] ?? 2048}+ value={draft.max_total_mb}+ onChange={(event) =>+ setField("max_total_mb")(Number(event.target.value))+ }+ />+ }+ />+ </SettingSection>++ <SettingSection+ title={t("Extraction budgets")}+ description={t(+ "Documents are converted to text and inlined into the model context. These budgets bound how much text a single file and a whole message may contribute — raise them for large documents, at the cost of context window and tokens.",+ )}+ >+ <SettingRow+ title={t("Max characters per document")}+ description={t(+ "Text extracted beyond this from one file is truncated with a notice.",+ )}+ control={+ <input+ className={`${inputClass} w-36`}+ type="number"+ min={bounds?.chars[0] ?? 10000}+ max={bounds?.chars[1] ?? 5000000}+ step={10000}+ value={draft.max_chars_per_doc}+ onChange={(event) =>+ setField("max_chars_per_doc")(Number(event.target.value))+ }+ />+ }+ />+ <SettingRow+ title={t("Max characters per message")}+ description={t(+ "Total extracted text across all documents on one message.",+ )}+ control={+ <input+ className={`${inputClass} w-36`}+ type="number"+ min={bounds?.chars[0] ?? 10000}+ max={bounds?.chars[1] ?? 5000000}+ step={10000}+ value={draft.max_chars_total}+ onChange={(event) =>+ setField("max_chars_total")(Number(event.target.value))+ }+ />+ }+ />+ </SettingSection>++ <p className="mt-2 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Note: images are sent to the model provider as-is — provider-side size limits still apply regardless of these caps.",+ )}+ </p>+ </>+ )}+ </div>+ );+}diff --git a/web/features/settings/sections/CapabilitiesSettingsSection.tsx b/web/features/settings/sections/CapabilitiesSettingsSection.tsxnew file mode 100644index 000000000..d10390e78--- /dev/null+++ b/web/features/settings/sections/CapabilitiesSettingsSection.tsx@@ -0,0 +1,609 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";++import { apiFetch, apiUrl } from "@/lib/api";+import { EXTENSION_ENDPOINTS } from "@/lib/settings-extensions";+import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+} from "@/components/settings/shared";+import { useSettings } from "@/features/settings/store/SettingsStore";++// ── Shape mirrors deeptutor/services/config/capabilities_settings.py ──────++interface SimpleLLMBlock {+ temperature: number;+ max_tokens: number;+}++interface ChatBlock {+ temperature: number;+ max_rounds: number;+ stage_budgets: {+ exploring: number;+ responding: number;+ };+}++interface ResearchExtras {+ researching: {+ note_agent_mode: string;+ tool_timeout: number;+ tool_max_retries: number;+ paper_search_years_limit: number;+ };+}++interface QuestionExtras {+ exploring: {+ max_iterations: number;+ tool_summarizer: {+ enabled: boolean;+ max_tokens: number;+ };+ };+}++interface SolveExtras {+ max_rounds: number;+ max_replans: number;+}++interface CapabilitiesSettingsDTO {+ chat: ChatBlock;+ solve: SimpleLLMBlock & SolveExtras;+ research: SimpleLLMBlock & ResearchExtras;+ question: SimpleLLMBlock & QuestionExtras;+ co_writer: SimpleLLMBlock;+ vision_solver: SimpleLLMBlock;+ math_animator: SimpleLLMBlock;+}++function isValidCapabilitiesDTO(+ value: unknown,+): value is CapabilitiesSettingsDTO {+ if (!value || typeof value !== "object") return false;+ const v = value as Record<string, unknown>;+ const chat = v.chat as Record<string, unknown> | undefined;+ const solve = v.solve as Record<string, unknown> | undefined;+ return (+ !!chat &&+ typeof chat.temperature === "number" &&+ typeof chat.max_rounds === "number" &&+ !!chat.stage_budgets &&+ !!solve &&+ typeof solve.max_rounds === "number" &&+ typeof solve.max_replans === "number" &&+ !!v.research &&+ !!v.question+ );+}++export default function CapabilitiesSettingsPage() {+ const { t } = useTranslation();+ const { registerExtension, pendingExtensionPayload, draftRevision } =+ useSettings();+ const [settings, setSettings] = useState<CapabilitiesSettingsDTO | null>(+ null,+ );+ const [serverSnapshot, setServerSnapshot] =+ useState<CapabilitiesSettingsDTO | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);++ const load = useCallback(async () => {+ try {+ const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.capabilities));+ if (!res.ok) {+ setLoadError(+ t(+ "Failed to load capability settings (HTTP {{status}}). Make sure the backend is running the latest build — the /api/v1/capabilities/settings endpoint was added in this release.",+ { status: res.status },+ ),+ );+ return;+ }+ const data: unknown = await res.json();+ if (!isValidCapabilitiesDTO(data)) {+ setLoadError(+ t(+ "The backend returned an unexpected payload for /api/v1/capabilities/settings. Restart the backend to pick up the latest schema.",+ ),+ );+ return;+ }+ const pending = pendingExtensionPayload("capabilities") as+ | CapabilitiesSettingsDTO+ | undefined;+ setSettings(pending ?? data);+ setServerSnapshot(data);+ setLoadError(null);+ } catch (err) {+ setLoadError(+ err instanceof Error+ ? err.message+ : t("Failed to load capability settings."),+ );+ }+ }, [pendingExtensionPayload, t]);++ useEffect(() => {+ const timer = window.setTimeout(() => {+ void load();+ }, 0);+ return () => window.clearTimeout(timer);+ // Re-read when a draft is discarded so the page drops its stale copy.+ }, [draftRevision, load]);++ const dirty =+ !!settings &&+ !!serverSnapshot &&+ JSON.stringify(settings) !== JSON.stringify(serverSnapshot);++ const settingsRef = useRef(settings);+ useEffect(() => {+ settingsRef.current = settings;+ }, [settings]);+ const save = useCallback(async () => {+ const current = settingsRef.current;+ if (!current) return;+ const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.capabilities), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(current),+ });+ if (!res.ok) {+ throw new Error(+ t("Failed to save capability settings (HTTP {{status}})", {+ status: res.status,+ }),+ );+ }+ const data: unknown = await res.json();+ if (!isValidCapabilitiesDTO(data)) {+ throw new Error(t("Backend returned an unexpected payload after save."));+ }+ setSettings(data);+ setServerSnapshot(data);+ }, [t]);++ useEffect(() => {+ registerExtension("capabilities", { dirty, save, payload: settings });+ return () => registerExtension("capabilities", null);+ }, [dirty, save, settings, registerExtension]);++ function patchChat<K extends keyof ChatBlock>(key: K, value: ChatBlock[K]) {+ if (!settings) return;+ setSettings({ ...settings, chat: { ...settings.chat, [key]: value } });+ }++ function patchStageBudget(+ stage: keyof ChatBlock["stage_budgets"],+ value: number,+ ) {+ if (!settings) return;+ setSettings({+ ...settings,+ chat: {+ ...settings.chat,+ stage_budgets: { ...settings.chat.stage_budgets, [stage]: value },+ },+ });+ }++ function patchSimple(+ cap: "solve" | "co_writer" | "vision_solver" | "math_animator",+ value: Partial<SimpleLLMBlock>,+ ) {+ if (!settings) return;+ setSettings({ ...settings, [cap]: { ...settings[cap], ...value } });+ }++ function patchSolveExtras(value: Partial<SolveExtras>) {+ if (!settings) return;+ setSettings({ ...settings, solve: { ...settings.solve, ...value } });+ }++ function patchResearch(value: Partial<SimpleLLMBlock>) {+ if (!settings) return;+ setSettings({ ...settings, research: { ...settings.research, ...value } });+ }++ function patchResearching(value: Partial<ResearchExtras["researching"]>) {+ if (!settings) return;+ setSettings({+ ...settings,+ research: {+ ...settings.research,+ researching: { ...settings.research.researching, ...value },+ },+ });+ }++ function patchQuestion(value: Partial<SimpleLLMBlock>) {+ if (!settings) return;+ setSettings({ ...settings, question: { ...settings.question, ...value } });+ }++ function patchExploring(value: Partial<QuestionExtras["exploring"]>) {+ if (!settings) return;+ setSettings({+ ...settings,+ question: {+ ...settings.question,+ exploring: { ...settings.question.exploring, ...value },+ },+ });+ }++ function patchExploringSummarizer(+ value: Partial<QuestionExtras["exploring"]["tool_summarizer"]>,+ ) {+ if (!settings) return;+ setSettings({+ ...settings,+ question: {+ ...settings.question,+ exploring: {+ ...settings.question.exploring,+ tool_summarizer: {+ ...settings.question.exploring.tool_summarizer,+ ...value,+ },+ },+ },+ });+ }++ if (loadError) {+ return (+ <div className="grid h-[60vh] place-items-center px-6">+ <div className="max-w-xl rounded-lg border border-[var(--border)] bg-[var(--background)] p-4 text-[13px] text-[var(--muted-foreground)]">+ <div className="mb-2 font-medium text-[var(--foreground)]">+ {t("Couldn't load capability settings")}+ </div>+ <div>{loadError}</div>+ <button+ type="button"+ onClick={() => void load()}+ className="mt-3 rounded-md border border-[var(--border)] bg-[var(--card)] px-3 py-1 text-[12px] hover:bg-[var(--muted)]"+ >+ {t("Retry")}+ </button>+ </div>+ </div>+ );+ }++ if (!settings) {+ return (+ <div className="grid h-[60vh] place-items-center text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ );+ }++ return (+ <div data-tour="tour-capabilities">+ <SettingsPageHeader+ title={t("Capabilities")}+ description={t("Per-capability LLM parameters and runtime knobs.")}+ />++ <SettingSection+ title={t("Chat")}+ description={t(+ "Exploring agent loop followed by a respond stage. Stage budgets cap max_tokens per LLM round.",+ )}+ >+ <NumberRow+ label={t("Temperature")}+ help={t("Sampling temperature shared across every chat stage.")}+ value={settings.chat.temperature}+ onChange={(n) => patchChat("temperature", n)}+ min={0}+ max={2}+ step={0.05}+ isFloat+ />+ <NumberRow+ label={t("Max rounds")}+ help={t(+ "Hard cap on exploring-loop LLM rounds per turn. A round without tool calls ends the loop early.",+ )}+ value={settings.chat.max_rounds}+ onChange={(n) => patchChat("max_rounds", n)}+ min={1}+ max={50}+ />+ <NumberRow+ label={t("Exploring (max tokens)")}+ help={t("Budget per exploring-loop round (notes + tool calls).")}+ value={settings.chat.stage_budgets.exploring}+ onChange={(n) => patchStageBudget("exploring", n)}+ min={256}+ max={200000}+ step={100}+ />+ <NumberRow+ label={t("Responding (max tokens)")}+ help={t("Budget for the final user-facing response.")}+ value={settings.chat.stage_budgets.responding}+ onChange={(n) => patchStageBudget("responding", n)}+ min={256}+ max={200000}+ step={100}+ />+ </SettingSection>++ <SettingSection+ title={t("Solve")}+ description={t(+ "Deep solve runs as one agent loop with a plan / finish-step / replan spine.",+ )}+ >+ <NumberRow+ label={t("Temperature")}+ value={settings.solve.temperature}+ onChange={(n) => patchSimple("solve", { temperature: n })}+ min={0}+ max={2}+ step={0.05}+ isFloat+ />+ <NumberRow+ label={t("Max tokens")}+ value={settings.solve.max_tokens}+ onChange={(n) => patchSimple("solve", { max_tokens: n })}+ min={256}+ max={200000}+ step={100}+ />+ <NumberRow+ label={t("Max rounds")}+ help={t(+ "Total LLM-round budget for one solve turn (plan, tool calls and finishing all count).",+ )}+ value={settings.solve.max_rounds}+ onChange={(n) => patchSolveExtras({ max_rounds: n })}+ min={1}+ max={50}+ />+ <NumberRow+ label={t("Max replans")}+ help={t(+ "How many times the planner may revise the plan within one turn.",+ )}+ value={settings.solve.max_replans}+ onChange={(n) => patchSolveExtras({ max_replans: n })}+ min={0}+ max={10}+ />+ </SettingSection>++ <SettingSection+ title={t("Question")}+ description={t("Deep question (quiz) generation pipeline.")}+ >+ <NumberRow+ label={t("Temperature")}+ value={settings.question.temperature}+ onChange={(n) => patchQuestion({ temperature: n })}+ min={0}+ max={2}+ step={0.05}+ isFloat+ />+ <NumberRow+ label={t("Max tokens")}+ value={settings.question.max_tokens}+ onChange={(n) => patchQuestion({ max_tokens: n })}+ min={256}+ max={200000}+ step={100}+ />+ <NumberRow+ label={t("Explore max iterations")}+ help={t("Cap on the explore loop before planning.")}+ value={settings.question.exploring.max_iterations}+ onChange={(n) => patchExploring({ max_iterations: n })}+ min={1}+ max={50}+ />+ <ToggleRow+ label={t("Tool summarizer enabled")}+ help={t("Summarize long tool outputs to keep the prompt budget low.")}+ value={settings.question.exploring.tool_summarizer.enabled}+ onChange={(v) => patchExploringSummarizer({ enabled: v })}+ />+ <NumberRow+ label={t("Tool summarizer (max tokens)")}+ value={settings.question.exploring.tool_summarizer.max_tokens}+ onChange={(n) => patchExploringSummarizer({ max_tokens: n })}+ min={128}+ max={200000}+ step={100}+ />+ </SettingSection>++ <SettingSection+ title={t("Research")}+ description={t(+ "Deep research pipeline. Iteration count is controlled per request via the depth selector (quick / standard / deep / manual) in the chat input, not here.",+ )}+ >+ <NumberRow+ label={t("Temperature")}+ value={settings.research.temperature}+ onChange={(n) => patchResearch({ temperature: n })}+ min={0}+ max={2}+ step={0.05}+ isFloat+ />+ <NumberRow+ label={t("Max tokens")}+ value={settings.research.max_tokens}+ onChange={(n) => patchResearch({ max_tokens: n })}+ min={256}+ max={200000}+ step={100}+ />+ <NumberRow+ label={t("Tool timeout (s)")}+ help={t("Per-tool wall-clock timeout for the researching phase.")}+ value={settings.research.researching.tool_timeout}+ onChange={(n) => patchResearching({ tool_timeout: n })}+ min={1}+ max={600}+ />+ <NumberRow+ label={t("Tool max retries")}+ value={settings.research.researching.tool_max_retries}+ onChange={(n) => patchResearching({ tool_max_retries: n })}+ min={0}+ max={10}+ />+ <NumberRow+ label={t("Paper search years limit")}+ help={t("How far back paper search will scan.")}+ value={settings.research.researching.paper_search_years_limit}+ onChange={(n) => patchResearching({ paper_search_years_limit: n })}+ min={1}+ max={50}+ />+ </SettingSection>++ <SettingSection+ title={t("Math animator")}+ description={t("Manim animation / image generation pipeline.")}+ >+ <NumberRow+ label={t("Temperature")}+ value={settings.math_animator.temperature}+ onChange={(n) => patchSimple("math_animator", { temperature: n })}+ min={0}+ max={2}+ step={0.05}+ isFloat+ />+ <NumberRow+ label={t("Max tokens")}+ value={settings.math_animator.max_tokens}+ onChange={(n) => patchSimple("math_animator", { max_tokens: n })}+ min={256}+ max={200000}+ step={100}+ />+ </SettingSection>++ <SettingSection+ title={t("Co-writer")}+ description={t("Selection edit / inline rewrite agent.")}+ >+ <NumberRow+ label={t("Temperature")}+ value={settings.co_writer.temperature}+ onChange={(n) => patchSimple("co_writer", { temperature: n })}+ min={0}+ max={2}+ step={0.05}+ isFloat+ />+ <NumberRow+ label={t("Max tokens")}+ value={settings.co_writer.max_tokens}+ onChange={(n) => patchSimple("co_writer", { max_tokens: n })}+ min={256}+ max={200000}+ step={100}+ />+ </SettingSection>+ </div>+ );+}++// ── Field components (mirrors memory page) ─────────────────────────────++interface NumberRowProps {+ label: string;+ help?: string;+ value: number;+ onChange: (n: number) => void;+ min?: number;+ max?: number;+ step?: number;+ isFloat?: boolean;+}++function NumberRow({+ label,+ help,+ value,+ onChange,+ min,+ max,+ step = 1,+ isFloat = false,+}: NumberRowProps) {+ return (+ <SettingRow+ title={label}+ description={help}+ control={+ <input+ type="number"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => {+ const raw = e.target.value;+ if (raw === "") return;+ const n = isFloat ? parseFloat(raw) : parseInt(raw, 10);+ if (!Number.isNaN(n)) onChange(n);+ }}+ className="w-28 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-right text-[12px] outline-none focus:border-[var(--primary)]"+ />+ }+ />+ );+}++interface ToggleRowProps {+ label: string;+ help?: string;+ value: boolean;+ onChange: (v: boolean) => void;+}++function ToggleRow({ label, help, value, onChange }: ToggleRowProps) {+ return (+ <SettingRow+ title={label}+ description={help}+ control={+ <button+ type="button"+ role="switch"+ aria-checked={value}+ onClick={() => onChange(!value)}+ className={+ "relative inline-flex h-5 w-9 items-center rounded-full transition " ++ (value ? "bg-[var(--primary)]" : "bg-[var(--muted)]")+ }+ >+ <span+ className={+ "inline-block h-4 w-4 transform rounded-full bg-white shadow transition " ++ (value ? "translate-x-4" : "translate-x-0.5")+ }+ />+ </button>+ }+ />+ );+}diff --git a/web/features/settings/sections/ChatSettingsSection.tsx b/web/features/settings/sections/ChatSettingsSection.tsxnew file mode 100644index 000000000..1a15b2c91--- /dev/null+++ b/web/features/settings/sections/ChatSettingsSection.tsx@@ -0,0 +1,26 @@+"use client";++import { CategoryScroll } from "@/components/settings/CategoryScroll";++import VideoLearningSettingsPage from "./VideoLearningSettingsSection";+import ToolsSettingsPage from "./ToolsSettingsSection";+import CapabilitiesSettingsPage from "./CapabilitiesSettingsSection";+import StarterSettingsPage from "./StartersSettingsSection";+import AttachmentSettingsPage from "./AttachmentsSettingsSection";++/**+ * The Chat category, in full — see `ModelsSettingsPage` for the pattern.+ */+export default function ChatSettingsPage() {+ return (+ <CategoryScroll+ sections={[+ { key: "video-learning", Component: VideoLearningSettingsPage },+ { key: "tools", Component: ToolsSettingsPage },+ { key: "capabilities", Component: CapabilitiesSettingsPage },+ { key: "starters", Component: StarterSettingsPage },+ { key: "attachments", Component: AttachmentSettingsPage },+ ]}+ />+ );+}diff --git a/web/features/settings/sections/DocumentParsingSettingsSection.tsx b/web/features/settings/sections/DocumentParsingSettingsSection.tsxnew file mode 100644index 000000000..6d5ae769a--- /dev/null+++ b/web/features/settings/sections/DocumentParsingSettingsSection.tsx@@ -0,0 +1,1404 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { CheckCircle2, Download, Loader2, XCircle } from "lucide-react";+import { useTranslation } from "react-i18next";++import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+ inputClass,+ nativeSelectClass,+ selectOptionClass,+} from "@/components/settings/shared";+import { MinerUEngineSettings } from "@/components/settings/MinerUEngineSettings";+import { Toggle } from "@/components/settings/Toggle";+import { apiFetch, apiUrl } from "@/lib/api";++type EngineMeta = {+ id: string;+ name: string;+ description: string;+ needs_local_models: boolean;+ available: boolean;+};++type Readiness = { ready: boolean; reason: string; message: string };++type DocumentParsingPayload = {+ engine: string;+ engines: Record<string, Record<string, unknown>>;+ available_engines: EngineMeta[];+ readiness: Record<string, Readiness>;+ installable: string[];+ mineru: { api_token_set: boolean; local_cli?: unknown };+ docling?: { api_token_set: boolean };+};++const PIP_HINT: Record<string, string> = {+ docling: "pip install deeptutor[parse-docling]",+ markitdown: "pip install deeptutor[parse-markitdown]",+ pymupdf4llm: "pip install deeptutor[parse-pymupdf4llm]",+ liteparse: "pip install deeptutor[parse-liteparse]",+};++// Engine names and descriptions are returned by the backend so unknown or+// future engines can still render. Known descriptions use locale keys to keep+// the settings page translated without changing the API metadata contract.+const ENGINE_NAME_KEYS: Record<string, string> = {+ text_only: "Text-only",+};++const ENGINE_DESCRIPTION_KEYS: Record<string, string> = {+ text_only:+ "Built-in plain text extraction for PDF/Office/text files. No optional parser package, no model download, no layout structure.",+ mineru:+ "Highest-fidelity multimodal parsing (layout, tables, formulas). Local CLI downloads models, or use the hosted cloud API. Supports PDF, common images, DOCX, PPTX, and XLSX.",+ docling:+ "Structured document conversion (layout/tables). Runs the in-process docling package (downloads models on first run) or points at a remote Docling Serve server. PDF/Office/HTML/images.",+ markitdown:+ "Lightweight, no model downloads — broad format support, Markdown output. Works out of the box.",+ pymupdf4llm:+ "Lightweight, no model downloads or CUDA — runs on low-end / GPU-less machines. PDF/e-book → Markdown and can extract images. PDF and e-book formats only.",+ liteparse:+ "Fast, lightweight PDF parser with spatial text extraction. Markdown output, optional image extraction. No model downloads. Developed by LlamaIndex.",+ tika:+ "Remote Apache Tika server. Broad format support, no local install or model downloads. Point at an existing tika-server container.",+};++export default function DocumentParsingSettingsPage() {+ const { t } = useTranslation();+ const [data, setData] = useState<DocumentParsingPayload | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ const load = useCallback(async () => {+ setError(null);+ try {+ const response = await apiFetch(+ apiUrl("/api/v1/settings/document-parsing"),+ );+ const payload = (await response.json().catch(() => ({}))) as+ | DocumentParsingPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in payload && payload.detail+ ? payload.detail+ : t("Failed to load document parsing settings."),+ );+ }+ setData(payload as DocumentParsingPayload);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setLoading(false);+ }+ }, [t]);++ useEffect(() => {+ void load();+ }, [load]);++ const putDocumentParsing = useCallback(+ async (body: Record<string, unknown>) => {+ setBusy(true);+ setError(null);+ try {+ const response = await apiFetch(+ apiUrl("/api/v1/settings/document-parsing"),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ },+ );+ const payload = (await response.json().catch(() => ({}))) as+ | DocumentParsingPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in payload && payload.detail+ ? payload.detail+ : t("Failed to save document parsing settings."),+ );+ }+ setData(payload as DocumentParsingPayload);+ return true;+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ return false;+ } finally {+ setBusy(false);+ }+ },+ [t],+ );++ return (+ <div>+ <SettingsPageHeader+ title={t("Document Parsing")}+ description={t(+ "How uploaded documents are converted into text for knowledge bases and question generation. Pick an engine and its options. Local model downloads are off by default — they only happen when you explicitly allow them.",+ )}+ />++ {loading && (+ <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ {t("Loading...")}+ </div>+ )}++ {!loading && error && (+ <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">+ {error}+ </div>+ )}++ {!loading && data && (+ <>+ <section className="mb-10">+ <header className="mb-3">+ <h2 className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">+ {t("Engine")}+ </h2>+ <p className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "The active engine handles all parsing. Text-only is built in and extracts plain text; markitdown is lightweight and optional; MinerU and Docling produce richer structure, while Tika provides broad remote text extraction.",+ )}+ </p>+ </header>+ <div className="flex flex-col gap-2">+ {data.available_engines.map((engine) => {+ const active = engine.id === data.engine;+ const nameKey = ENGINE_NAME_KEYS[engine.id];+ const descriptionKey = ENGINE_DESCRIPTION_KEYS[engine.id];+ return (+ <button+ key={engine.id}+ type="button"+ disabled={busy}+ onClick={() =>+ !active && putDocumentParsing({ engine: engine.id })+ }+ className={`flex items-start justify-between gap-4 rounded-xl border px-4 py-3 text-left transition-colors disabled:opacity-60 ${+ active+ ? "border-[var(--foreground)] bg-[var(--card)]"+ : "border-[var(--border)] hover:border-[var(--foreground)]/40"+ }`}+ >+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-[13px] font-medium text-[var(--foreground)]">+ {nameKey ? t(nameKey) : engine.name}+ </span>+ {active && (+ <span className="rounded-full bg-[var(--foreground)] px-2 py-0.5 text-[10px] font-medium text-[var(--background)]">+ {t("Active")}+ </span>+ )}+ {!engine.available && (+ <span className="rounded-full border border-[var(--border)] px-2 py-0.5 text-[10px] text-[var(--muted-foreground)]">+ {t("Not installed")}+ </span>+ )}+ </div>+ <p className="mt-1 text-[12px] text-[var(--muted-foreground)]">+ {descriptionKey ? t(descriptionKey) : engine.description}+ </p>+ </div>+ </button>+ );+ })}+ </div>+ </section>++ {data.engine === "text_only" && <TextOnlyPanel />}++ {data.engine === "mineru" && <MinerUEngineSettings />}++ {data.engine === "docling" && (+ <DoclingPanel+ slice={data.engines.docling || {}}+ readiness={data.readiness.docling}+ available={+ data.available_engines.find((e) => e.id === "docling")+ ?.available ?? false+ }+ busy={busy}+ onInstalled={load}+ tokenSet={data.docling?.api_token_set ?? false}+ onSave={(patch) =>+ putDocumentParsing({ engines: { docling: patch } })+ }+ />+ )}++ {data.engine === "markitdown" && (+ <MarkItDownPanel+ slice={data.engines.markitdown || {}}+ available={+ data.available_engines.find((e) => e.id === "markitdown")+ ?.available ?? false+ }+ busy={busy}+ onInstalled={load}+ onSave={(patch) =>+ putDocumentParsing({ engines: { markitdown: patch } })+ }+ />+ )}++ {data.engine === "pymupdf4llm" && (+ <PyMuPDF4LLMPanel+ slice={data.engines.pymupdf4llm || {}}+ available={+ data.available_engines.find((e) => e.id === "pymupdf4llm")+ ?.available ?? false+ }+ busy={busy}+ onInstalled={load}+ onSave={(patch) =>+ putDocumentParsing({ engines: { pymupdf4llm: patch } })+ }+ />+ )}++ {data.engine === "liteparse" && (+ <LiteParsePanel+ slice={data.engines.liteparse || {}}+ available={+ data.available_engines.find((e) => e.id === "liteparse")+ ?.available ?? false+ }+ busy={busy}+ onInstalled={load}+ onSave={(patch) =>+ putDocumentParsing({ engines: { liteparse: patch } })+ }+ />+ )}++ {data.engine === "tika" && (+ <TikaPanel+ slice={data.engines.tika || {}}+ readiness={data.readiness.tika}+ busy={busy}+ onSave={(patch) =>+ putDocumentParsing({ engines: { tika: patch } })+ }+ />+ )}+ </>+ )}+ </div>+ );+}++function TextOnlyPanel() {+ const { t } = useTranslation();+ return (+ <SettingSection+ title={t("Text-only")}+ description={t(+ "Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.",+ )}+ >+ <SettingRow+ title={t("Model status")}+ control={+ <ReadinessBadge+ readiness={{ ready: true, reason: "ready", message: "" }}+ />+ }+ />+ </SettingSection>+ );+}++function ReadinessBadge({ readiness }: { readiness?: Readiness }) {+ const { t } = useTranslation();+ if (!readiness) return null;+ return (+ <span+ className={`inline-flex items-center gap-1 text-[12px] ${+ readiness.ready+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-amber-600 dark:text-amber-400"+ }`}+ >+ {readiness.ready ? (+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />+ ) : (+ <XCircle className="h-3.5 w-3.5 shrink-0" />+ )}+ {readiness.ready ? t("Ready to parse.") : t(readiness.message)}+ </span>+ );+}++// Full-width readiness line for engines whose "not ready" guidance is a+// multi-sentence message (e.g. Docling's "models not downloaded" hint). A long+// message must wrap full-width — it doesn't fit a SettingRow's compact,+// non-shrinking control slot (which overflows and squeezes the title).+function ReadinessNotice({ readiness }: { readiness?: Readiness }) {+ const { t } = useTranslation();+ if (!readiness) return null;+ if (readiness.ready) {+ return (+ <div className="flex items-center gap-1.5 py-3.5 text-[12px] text-emerald-600 dark:text-emerald-400">+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />+ {t("Ready to parse.")}+ </div>+ );+ }+ return (+ <div className="py-3.5">+ <div className="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[12px] leading-relaxed text-amber-700 dark:text-amber-300">+ <XCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ <span className="min-w-0">{t(readiness.message)}</span>+ </div>+ </div>+ );+}++const DOCLING_MODES = ["local", "remote"] as const;+const DEFAULT_DOCLING_URL = "http://localhost:5001";+const TOKEN_MASK = "••••••••••••";++function DoclingPanel({+ slice,+ readiness,+ available,+ busy,+ tokenSet,+ onInstalled,+ onSave,+}: {+ slice: Record<string, unknown>;+ readiness?: Readiness;+ available: boolean;+ busy: boolean;+ tokenSet: boolean;+ onInstalled: () => void;+ onSave: (patch: Record<string, unknown>) => Promise<boolean>;+}) {+ const { t } = useTranslation();+ const mode =+ slice.mode === "remote"+ ? "remote"+ : slice.mode === "local"+ ? "local"+ : "local";+ const isRemote = mode === "remote";+ const doOcr = Boolean(slice.do_ocr);+ const doTables = slice.do_table_structure !== false;+ const allowDownload = Boolean(slice.allow_local_model_download);++ // Remote server URL + API key are edited as a draft and saved together so a+ // half-typed URL is never used mid-parse. Token is write-only.+ const [remoteDraft, setRemoteDraft] = useState({+ url: (typeof slice.api_base_url === "string" && slice.api_base_url) || "",+ });+ const [tokenDraft, setTokenDraft] = useState("");+ const [tokenTouched, setTokenTouched] = useState(false);+ const [savingRemote, setSavingRemote] = useState(false);+ const [testing, setTesting] = useState(false);+ const [testResult, setTestResult] = useState<{+ ok: boolean;+ message: string;+ } | null>(null);+ const [remoteMsg, setRemoteMsg] = useState("");++ async function saveRemote() {+ setSavingRemote(true);+ setRemoteMsg("");+ setTestResult(null);+ const patch: Record<string, unknown> = {+ mode: "remote",+ api_base_url: remoteDraft.url.trim() || DEFAULT_DOCLING_URL,+ };+ if (tokenTouched) patch.api_token = tokenDraft;+ try {+ const saved = await onSave(patch);+ if (saved) {+ setRemoteMsg(t("Remote Docling settings saved."));+ setTokenDraft("");+ setTokenTouched(false);+ }+ } finally {+ setSavingRemote(false);+ }+ }++ async function testConnection() {+ setTesting(true);+ setTestResult(null);+ try {+ const body: Record<string, unknown> = {+ api_base_url: remoteDraft.url.trim() || DEFAULT_DOCLING_URL,+ };+ if (tokenTouched) body.api_token = tokenDraft;+ const response = await apiFetch(+ apiUrl("/api/v1/settings/document-parsing/docling/test"),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ },+ );+ const data = (await response.json().catch(() => ({}))) as {+ ok?: boolean;+ message?: string;+ detail?: string;+ };+ if (!response.ok) {+ setTestResult({+ ok: false,+ message: data.detail || t("Connection test failed."),+ });+ return;+ }+ setTestResult({+ ok: Boolean(data.ok),+ message:+ data.message ||+ (data.ok ? t("Ready to parse.") : t("Connection test failed.")),+ });+ } catch (err) {+ setTestResult({+ ok: false,+ message: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setTesting(false);+ }+ }++ const notInstalled = !available && !isRemote;++ return (+ <>+ <SettingSection+ title={t("Docling backend")}+ description={t(+ "Choose where parsing runs: the in-process docling package (local) or a Docling Serve server (remote).",+ )}+ >+ <SettingRow+ title={t("Mode")}+ description={+ isRemote+ ? t(+ "Documents are sent to a Docling Serve server for conversion.",+ )+ : t(+ "Parsing runs on this machine using the installed docling package.",+ )+ }+ control={+ <div className="inline-flex rounded-lg border border-[var(--border)] p-0.5">+ {DOCLING_MODES.map((m) => (+ <button+ key={m}+ type="button"+ disabled={busy}+ onClick={() => {+ if (m !== mode) {+ onSave({ mode: m });+ setTestResult(null);+ }+ }}+ className={`rounded-md px-3 py-1 text-[12px] font-medium transition-colors disabled:opacity-40 ${+ mode === m+ ? "bg-[var(--foreground)] text-[var(--background)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {m === "local" ? t("Local") : t("Remote server")}+ </button>+ ))}+ </div>+ }+ />+ </SettingSection>++ {isRemote && (+ <SettingSection+ title={t("Remote server")}+ description={t(+ "Point at a Docling Serve server (e.g. `docling serve` or the docker image). No local docling install or models needed.",+ )}+ >+ <SettingRow+ title={t("Server base URL")}+ control={+ <input+ className={`${inputClass} w-[320px] max-w-[48vw] font-mono text-[12px]`}+ placeholder={DEFAULT_DOCLING_URL}+ value={remoteDraft.url}+ onChange={(e) => {+ setRemoteDraft({ url: e.target.value });+ setTestResult(null);+ }}+ />+ }+ />+ <SettingRow+ title={t("API key")}+ description={+ tokenSet+ ? t(+ "A key is saved. Type to replace it; leave blank to keep it.",+ )+ : t(+ "Optional. Sent as the X-Api-Key header for a secured server.",+ )+ }+ control={+ <input+ type="password"+ className={`${inputClass} w-[320px] max-w-[48vw]`}+ placeholder={tokenSet ? TOKEN_MASK : t("Optional API key")}+ value={tokenDraft}+ onChange={(e) => {+ setTokenDraft(e.target.value);+ setTokenTouched(true);+ }}+ />+ }+ />+ <SettingRow+ title={t("Test connection")}+ description={t("Pings the server health + version endpoints.")}+ control={+ <div className="flex items-center gap-3">+ {testResult && (+ <span+ className={`inline-flex max-w-[40vw] items-center gap-1 text-[12px] ${+ testResult.ok+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-red-600 dark:text-red-400"+ }`}+ >+ {testResult.ok ? (+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />+ ) : (+ <XCircle className="h-3.5 w-3.5 shrink-0" />+ )}+ {testResult.message}+ </span>+ )}+ <button+ type="button"+ onClick={testConnection}+ disabled={testing || savingRemote || busy}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-opacity hover:opacity-80 disabled:opacity-40"+ >+ {testing && <Loader2 className="h-3 w-3 animate-spin" />}+ {t("Test")}+ </button>+ <button+ type="button"+ onClick={saveRemote}+ disabled={savingRemote || busy}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"+ >+ {savingRemote && <Loader2 className="h-3 w-3 animate-spin" />}+ {t("Save remote server")}+ </button>+ </div>+ }+ />+ <div className="px-1 pb-4">+ <span className="text-[12px] text-[var(--muted-foreground)]">+ {remoteMsg ||+ t(+ "Settings are written to data/user/settings/document_parsing.json.",+ )}+ </span>+ </div>+ </SettingSection>+ )}++ {isRemote && (+ <SettingSection+ title={t("Parsing options")}+ description={t("Forwarded to the Docling server for each document.")}+ >+ <SettingRow+ title={t("Recognize tables")}+ control={+ <Toggle+ checked={doTables}+ disabled={busy}+ onChange={(v) => onSave({ do_table_structure: v })}+ />+ }+ />+ <SettingRow+ title={t("OCR scanned pages")}+ description={t("Slower; enable for image-only PDFs.")}+ control={+ <Toggle+ checked={doOcr}+ disabled={busy}+ onChange={(v) => onSave({ do_ocr: v })}+ />+ }+ />+ </SettingSection>+ )}++ {!isRemote && notInstalled && (+ <NotInstalledSection+ engineId="docling"+ title={t("Docling (local)")}+ onInstalled={onInstalled}+ />+ )}++ {!isRemote && !notInstalled && (+ <SettingSection+ title={t("Docling (local)")}+ description={t(+ "Structured conversion of PDF/Office/HTML/images. Downloads layout/table models on first run.",+ )}+ >+ <ReadinessNotice readiness={readiness} />+ {readiness && !readiness.ready && (+ <ModelDownloadRow+ engineId="docling"+ title={t("Docling")}+ onDownloaded={onInstalled}+ />+ )}+ <SettingRow+ title={t("Allow automatic model download")}+ description={t(+ "Off by default. When off, parsing fails with guidance instead of silently downloading models. Or pre-fetch with `docling-tools models download`.",+ )}+ control={+ <Toggle+ checked={allowDownload}+ disabled={busy}+ onChange={(v) => onSave({ allow_local_model_download: v })}+ />+ }+ />+ <SettingRow+ title={t("Recognize tables")}+ control={+ <Toggle+ checked={doTables}+ disabled={busy}+ onChange={(v) => onSave({ do_table_structure: v })}+ />+ }+ />+ <SettingRow+ title={t("OCR scanned pages")}+ description={t("Slower; enable for image-only PDFs.")}+ control={+ <Toggle+ checked={doOcr}+ disabled={busy}+ onChange={(v) => onSave({ do_ocr: v })}+ />+ }+ />+ </SettingSection>+ )}+ </>+ );+}++const DEFAULT_TIKA_URL = "http://localhost:9998";++function TikaPanel({+ slice,+ readiness,+ busy,+ onSave,+}: {+ slice: Record<string, unknown>;+ readiness?: Readiness;+ busy: boolean;+ onSave: (patch: Record<string, unknown>) => Promise<boolean>;+}) {+ const { t } = useTranslation();+ const [draftUrl, setDraftUrl] = useState(+ (typeof slice.server_url === "string" && slice.server_url) || "",+ );+ const [saving, setSaving] = useState(false);+ const [testing, setTesting] = useState(false);+ const [testResult, setTestResult] = useState<{+ ok: boolean;+ message: string;+ } | null>(null);++ async function save() {+ setSaving(true);+ setTestResult(null);+ try {+ await onSave({ server_url: draftUrl.trim() || DEFAULT_TIKA_URL });+ } finally {+ setSaving(false);+ }+ }++ async function testConnection() {+ setTesting(true);+ setTestResult(null);+ try {+ const response = await apiFetch(+ apiUrl("/api/v1/settings/document-parsing/tika/test"),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ server_url: draftUrl.trim() || DEFAULT_TIKA_URL,+ }),+ },+ );+ const data = (await response.json().catch(() => ({}))) as {+ ok?: boolean;+ message?: string;+ detail?: string;+ };+ if (!response.ok) {+ setTestResult({+ ok: false,+ message: data.detail || t("Connection test failed."),+ });+ return;+ }+ setTestResult({+ ok: Boolean(data.ok),+ message:+ data.message ||+ (data.ok ? t("Ready to parse.") : t("Connection test failed.")),+ });+ } catch (err) {+ setTestResult({+ ok: false,+ message: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setTesting(false);+ }+ }++ return (+ <SettingSection+ title={t("Tika")}+ description={t(+ "Point at an Apache Tika server (e.g. the apache/tika docker image). No local install or models needed.",+ )}+ >+ <ReadinessNotice readiness={readiness} />+ <SettingRow+ title={t("Server base URL")}+ control={+ <input+ className={`${inputClass} w-[320px] max-w-[48vw] font-mono text-[12px]`}+ placeholder={DEFAULT_TIKA_URL}+ value={draftUrl}+ onChange={(e) => {+ setDraftUrl(e.target.value);+ setTestResult(null);+ }}+ />+ }+ />+ <SettingRow+ title={t("Test connection")}+ description={t("Pings the server /version endpoint.")}+ control={+ <div className="flex items-center gap-3">+ {testResult && (+ <span+ className={`inline-flex max-w-[40vw] items-center gap-1 text-[12px] ${+ testResult.ok+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-red-600 dark:text-red-400"+ }`}+ >+ {testResult.ok ? (+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />+ ) : (+ <XCircle className="h-3.5 w-3.5 shrink-0" />+ )}+ {testResult.message}+ </span>+ )}+ <button+ type="button"+ onClick={testConnection}+ disabled={testing || saving || busy}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-opacity hover:opacity-80 disabled:opacity-40"+ >+ {testing && <Loader2 className="h-3 w-3 animate-spin" />}+ {t("Test")}+ </button>+ <button+ type="button"+ onClick={save}+ disabled={saving || busy}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"+ >+ {saving && <Loader2 className="h-3 w-3 animate-spin" />}+ {t("Save Tika server")}+ </button>+ </div>+ }+ />+ <div className="px-1 pb-4">+ <span className="text-[12px] text-[var(--muted-foreground)]">+ {t(+ "Settings are written to data/user/settings/document_parsing.json.",+ )}+ </span>+ </div>+ </SettingSection>+ );+}++function MarkItDownPanel({+ slice,+ available,+ busy,+ onInstalled,+ onSave,+}: {+ slice: Record<string, unknown>;+ available: boolean;+ busy: boolean;+ onInstalled: () => void;+ onSave: (patch: Record<string, unknown>) => void;+}) {+ const { t } = useTranslation();+ const llmImages = Boolean(slice.enable_llm_image_description);++ if (!available) {+ return (+ <NotInstalledSection+ engineId="markitdown"+ title={t("markitdown")}+ onInstalled={onInstalled}+ />+ );+ }++ return (+ <SettingSection+ title={t("markitdown")}+ description={t(+ "Lightweight Markdown conversion with broad format support. No model downloads.",+ )}+ >+ <SettingRow+ title={t("Describe images with the vision model")}+ description={t(+ "Reserved — uses DeepTutor's vision model to caption images during conversion.",+ )}+ control={+ <Toggle+ checked={llmImages}+ disabled={busy}+ onChange={(v) => onSave({ enable_llm_image_description: v })}+ />+ }+ />+ </SettingSection>+ );+}++const PYMUPDF4LLM_IMAGE_FORMATS = ["png", "jpg", "jpeg", "webp"];++function PyMuPDF4LLMPanel({+ slice,+ available,+ busy,+ onInstalled,+ onSave,+}: {+ slice: Record<string, unknown>;+ available: boolean;+ busy: boolean;+ onInstalled: () => void;+ onSave: (patch: Record<string, unknown>) => void;+}) {+ const { t } = useTranslation();+ const writeImages = slice.write_images !== false;+ const imageFormat =+ typeof slice.image_format === "string" ? slice.image_format : "png";+ const imageDpi = typeof slice.image_dpi === "number" ? slice.image_dpi : 150;++ if (!available) {+ return (+ <NotInstalledSection+ engineId="pymupdf4llm"+ title={t("PyMuPDF4LLM")}+ onInstalled={onInstalled}+ />+ );+ }++ return (+ <SettingSection+ title={t("PyMuPDF4LLM")}+ description={t(+ "Lightweight PDF/e-book → Markdown built on PyMuPDF. No model downloads or CUDA, so it runs on low-end machines.",+ )}+ >+ <SettingRow+ title={t("Extract images")}+ description={t(+ "Save embedded images and rendered vector graphics into the parse, referenced from the Markdown.",+ )}+ control={+ <Toggle+ checked={writeImages}+ disabled={busy}+ onChange={(v) => onSave({ write_images: v })}+ />+ }+ />+ {writeImages && (+ <>+ <SettingRow+ title={t("Image format")}+ control={+ <select+ className={`${nativeSelectClass} w-28`}+ value={imageFormat}+ disabled={busy}+ onChange={(e) => onSave({ image_format: e.target.value })}+ >+ {PYMUPDF4LLM_IMAGE_FORMATS.map((f) => (+ <option key={f} className={selectOptionClass} value={f}>+ {f}+ </option>+ ))}+ </select>+ }+ />+ <SettingRow+ title={t("Image resolution (DPI)")}+ description={t("Higher is sharper but larger. 72–600.")}+ control={+ <input+ type="number"+ min={72}+ max={600}+ step={1}+ value={imageDpi}+ disabled={busy}+ onChange={(e) => {+ const v = Number(e.target.value);+ if (Number.isFinite(v)) onSave({ image_dpi: v });+ }}+ className="w-24 rounded-lg border border-[var(--border)] bg-transparent px-2 py-1 text-[12px] text-[var(--foreground)]"+ />+ }+ />+ </>+ )}+ </SettingSection>+ );+}++function LiteParsePanel({+ slice,+ available,+ busy,+ onInstalled,+ onSave,+}: {+ slice: Record<string, unknown>;+ available: boolean;+ busy: boolean;+ onInstalled: () => void;+ onSave: (patch: Record<string, unknown>) => void;+}) {+ const { t } = useTranslation();+ const imageMode =+ typeof slice.image_mode === "string" ? slice.image_mode : "placeholder";+ const extractLinks = slice.extract_links !== false;+ const extractImages = Boolean(slice.extract_images);+ const maxPages = typeof slice.max_pages === "number" ? slice.max_pages : 0;++ if (!available) {+ return (+ <NotInstalledSection+ engineId="liteparse"+ title={t("LiteParse")}+ onInstalled={onInstalled}+ />+ );+ }++ return (+ <SettingSection+ title={t("LiteParse")}+ description={t(+ "Fast Rust-backed PDF/Office/image parser from LlamaIndex. Markdown output, no model downloads.",+ )}+ >+ <SettingRow+ title={t("Image mode")}+ description={t("How images are represented in the output.")}+ control={+ <select+ className={nativeSelectClass + " w-32"}+ value={imageMode}+ disabled={busy}+ onChange={(e) => onSave({ image_mode: e.target.value })}+ >+ {["placeholder", "off", "embed"].map((m) => (+ <option key={m} className={selectOptionClass} value={m}>+ {m}+ </option>+ ))}+ </select>+ }+ />+ <SettingRow+ title={t("Extract links")}+ description={t("Render [text](url) links in markdown output.")}+ control={+ <Toggle+ checked={extractLinks}+ disabled={busy}+ onChange={(v) => onSave({ extract_links: v })}+ />+ }+ />+ <SettingRow+ title={t("Extract images")}+ description={t("Save embedded images alongside the parsed Markdown.")}+ control={+ <Toggle+ checked={extractImages}+ disabled={busy}+ onChange={(v) => onSave({ extract_images: v })}+ />+ }+ />+ <SettingRow+ title={t("Max pages")}+ description={t("0 = unlimited. Limit pages parsed per document.")}+ control={+ <input+ type="number"+ min={0}+ step={1}+ value={maxPages}+ disabled={busy}+ onChange={(e) => {+ const v = Number(e.target.value);+ if (Number.isFinite(v) && v >= 0) onSave({ max_pages: v });+ }}+ className="w-24 rounded-lg border border-[var(--border)] bg-transparent px-2 py-1 text-[12px] text-[var(--foreground)]"+ />+ }+ />+ </SettingSection>+ );+}++type JobKind = "install" | "models";++type JobStatus = {+ state: "running" | "done" | "failed" | "cancelled" | string;+ kind: JobKind;+ lines: string[];+ message: string;+};++// Shared driver for the page's one-click background jobs (pip install / model+// download). Mirrors the MinerU model-download UI: POST to start → poll a shared+// cursor-based log filtered by `kind` → call onDone once on success. Only one+// job runs server-side at a time, so the kind filter keeps each card's view to+// its own job.+function useBackgroundJob(+ kind: JobKind,+ startUrl: string,+ engineId: string,+ onDone: () => void,+) {+ const { t } = useTranslation();+ const [job, setJob] = useState<JobStatus | null>(null);+ const [starting, setStarting] = useState(false);+ const cursor = useRef(0);+ const notifiedDone = useRef(false);++ useEffect(() => {+ if (job?.state !== "running") return;+ const timer = setInterval(async () => {+ try {+ const response = await apiFetch(+ apiUrl(+ `/api/v1/settings/document-parsing/job/status?cursor=${cursor.current}`,+ ),+ );+ if (!response.ok) return;+ const data = (await response.json()) as {+ state?: string;+ kind?: string;+ lines?: string[];+ next_cursor?: number;+ message?: string;+ };+ // A different kind of job is running — leave our view alone.+ if (data.kind && data.kind !== kind) return;+ cursor.current = data.next_cursor ?? cursor.current;+ setJob((current) =>+ current+ ? {+ state: data.state || current.state,+ kind,+ lines: [...current.lines, ...(data.lines || [])].slice(-100),+ message: data.message || "",+ }+ : current,+ );+ if (data.state === "done" && !notifiedDone.current) {+ notifiedDone.current = true;+ onDone();+ }+ } catch {+ // transient network error — keep polling+ }+ }, 1000);+ return () => clearInterval(timer);+ }, [job?.state, kind, onDone]);++ async function start() {+ setStarting(true);+ notifiedDone.current = false;+ try {+ const response = await apiFetch(apiUrl(startUrl), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ engine: engineId }),+ });+ const data = (await response.json().catch(() => ({}))) as {+ ok?: boolean;+ message?: string;+ detail?: string;+ };+ if (!response.ok || !data.ok) {+ setJob({+ state: "failed",+ kind,+ lines: [],+ message: data.message || data.detail || t("Failed."),+ });+ return;+ }+ cursor.current = 0;+ setJob({ state: "running", kind, lines: [], message: "" });+ } finally {+ setStarting(false);+ }+ }++ async function cancel() {+ try {+ await apiFetch(apiUrl("/api/v1/settings/document-parsing/job/cancel"), {+ method: "POST",+ });+ } catch {+ // status polling surfaces the final state either way+ }+ }++ return { job, starting, start, cancel };+}++// Status line + streamed log for a background job, shared by install / download.+function JobLog({+ job,+ runningLabel,+ doneLabel,+}: {+ job: JobStatus | null;+ runningLabel: string;+ doneLabel: string;+}) {+ if (!job) return null;+ return (+ <div className="px-1 pb-1">+ <div+ className={`mb-2 inline-flex items-center gap-1.5 text-[12px] ${+ job.state === "done"+ ? "text-emerald-600 dark:text-emerald-400"+ : job.state === "running"+ ? "text-[var(--muted-foreground)]"+ : "text-red-600 dark:text-red-400"+ }`}+ >+ {job.state === "running" ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : job.state === "done" ? (+ <CheckCircle2 className="h-3.5 w-3.5" />+ ) : (+ <XCircle className="h-3.5 w-3.5" />+ )}+ {job.state === "running"+ ? runningLabel+ : job.state === "done"+ ? doneLabel+ : job.message || job.state}+ </div>+ {job.lines.length > 0 && (+ <pre className="max-h-40 overflow-y-auto whitespace-pre-wrap rounded-lg border border-[var(--border)]/60 bg-[var(--card)] px-3 py-2 font-mono text-[11px] leading-relaxed text-[var(--muted-foreground)]">+ {job.lines.join("\n")}+ </pre>+ )}+ </div>+ );+}++function JobButton({+ running,+ starting,+ label,+ onStart,+ onCancel,+}: {+ running: boolean;+ starting: boolean;+ label: string;+ onStart: () => void;+ onCancel: () => void;+}) {+ const { t } = useTranslation();+ if (running) {+ return (+ <button+ type="button"+ onClick={onCancel}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-opacity hover:opacity-80"+ >+ {t("Cancel")}+ </button>+ );+ }+ return (+ <button+ type="button"+ onClick={onStart}+ disabled={starting}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"+ >+ {starting ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <Download className="h-3 w-3" />+ )}+ {label}+ </button>+ );+}++// The active engine's panel when its optional package isn't installed: a clean+// section with the pip hint and a one-click installer. Keeps install in ONE+// place per engine; reloads on success so the engine flips to available.+function NotInstalledSection({+ engineId,+ title,+ onInstalled,+}: {+ engineId: string;+ title: string;+ onInstalled: () => void;+}) {+ const { t } = useTranslation();+ const { job, starting, start, cancel } = useBackgroundJob(+ "install",+ "/api/v1/settings/document-parsing/install",+ engineId,+ onInstalled,+ );++ return (+ <SettingSection+ title={title}+ description={t(+ "Not installed yet. Install the package to use this engine — runs on the server, no terminal needed.",+ )}+ >+ <SettingRow+ title={t("Install package")}+ description={PIP_HINT[engineId]}+ control={+ <JobButton+ running={job?.state === "running"}+ starting={starting}+ label={t("Download & install")}+ onStart={start}+ onCancel={cancel}+ />+ }+ />+ <JobLog+ job={job}+ runningLabel={t("Installing {{name}}…", { name: title })}+ doneLabel={t("Installed. Reloading…")}+ />+ </SettingSection>+ );+}++// One-click model-weight download for an installed engine that still needs its+// models (e.g. Docling). Mirrors MinerU's "Download models"; reloads readiness+// on success so the gate clears.+function ModelDownloadRow({+ engineId,+ title,+ onDownloaded,+}: {+ engineId: string;+ title: string;+ onDownloaded: () => void;+}) {+ const { t } = useTranslation();+ const { job, starting, start, cancel } = useBackgroundJob(+ "models",+ "/api/v1/settings/document-parsing/models/download",+ engineId,+ onDownloaded,+ );++ return (+ <>+ <SettingRow+ title={t("Download models")}+ description={t(+ "Fetch the model weights onto the server now — no terminal needed.",+ )}+ control={+ <JobButton+ running={job?.state === "running"}+ starting={starting}+ label={t("Download models")}+ onStart={start}+ onCancel={cancel}+ />+ }+ />+ <JobLog+ job={job}+ runningLabel={t("Downloading {{name}} models…", { name: title })}+ doneLabel={t("Downloaded. Reloading…")}+ />+ </>+ );+}diff --git a/web/features/settings/sections/MemorySettingsSection.tsx b/web/features/settings/sections/MemorySettingsSection.tsxnew file mode 100644index 000000000..c87b2e5a7--- /dev/null+++ b/web/features/settings/sections/MemorySettingsSection.tsx@@ -0,0 +1,393 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";++import { apiFetch, apiUrl } from "@/lib/api";+import { EXTENSION_ENDPOINTS } from "@/lib/settings-extensions";+import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+} from "@/components/settings/shared";+import { useSettings } from "@/features/settings/store/SettingsStore";++interface MemorySettingsDTO {+ update: { l2_budget: number; l3_budget: number };+ audit: { l2_budget: number; l3_budget: number };+ dedup: { iterations: number; auto_after_update: boolean };+ merge: {+ auto_after_update: boolean;+ auto_after_audit: boolean;+ auto_after_dedup: boolean;+ };+ chunking: {+ overlap_ratio: number;+ boundary: "paragraph" | "sentence";+ min_chunk_chars: number;+ max_chunk_chars: number;+ };+ reference: {+ enforce_required: boolean;+ drop_invalid_refs: boolean;+ };+}++export default function MemorySettingsPage() {+ const { t } = useTranslation();+ const { registerExtension, pendingExtensionPayload, draftRevision } =+ useSettings();+ const [settings, setSettings] = useState<MemorySettingsDTO | null>(null);+ const [serverSnapshot, setServerSnapshot] =+ useState<MemorySettingsDTO | null>(null);++ useEffect(() => {+ let cancelled = false;+ void apiFetch(apiUrl(EXTENSION_ENDPOINTS.memory))+ .then((res) => res.json() as Promise<MemorySettingsDTO>)+ .then((data) => {+ if (cancelled) return;+ // A pending edit outlives the page it was made on; the server value is+ // the baseline dirtiness is measured against either way.+ const pending = pendingExtensionPayload("memory") as+ | MemorySettingsDTO+ | undefined;+ setSettings(pending ?? data);+ setServerSnapshot(data);+ });+ return () => {+ cancelled = true;+ };+ }, [draftRevision, pendingExtensionPayload]);++ const dirty =+ !!settings &&+ !!serverSnapshot &&+ JSON.stringify(settings) !== JSON.stringify(serverSnapshot);++ // Latest-save ref so the closure handed to registerExtension always+ // reflects the current settings without re-registering on each render.+ const settingsRef = useRef<MemorySettingsDTO | null>(null);+ useEffect(() => {+ settingsRef.current = settings;+ }, [settings]);+ const save = useCallback(async () => {+ const current = settingsRef.current;+ if (!current) return;+ const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.memory), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(current),+ });+ const data = (await res.json()) as MemorySettingsDTO;+ setSettings(data);+ setServerSnapshot(data);+ }, []);++ useEffect(() => {+ registerExtension("memory", { dirty, save, payload: settings });+ return () => registerExtension("memory", null);+ }, [dirty, save, settings, registerExtension]);++ function patch<K extends keyof MemorySettingsDTO>(+ key: K,+ value: Partial<MemorySettingsDTO[K]>,+ ) {+ if (!settings) return;+ setSettings({ ...settings, [key]: { ...settings[key], ...value } });+ }++ if (!settings) {+ return (+ <div className="grid h-[60vh] place-items-center text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ );+ }++ return (+ <div data-tour="tour-memory">+ <SettingsPageHeader+ title={t("Memory")}+ description={t(+ "Tune the chunk-based consolidator: how many LLM rounds per Update / Audit / Dedup, how aggressively to chunk, and how strictly to validate references.",+ )}+ />+ <SettingSection+ title={t("Update mode")}+ description={t(+ "Default LLM rounds for chunk-based incremental fact extraction. Per-doc overrides live in the workbench.",+ )}+ >+ <NumberRow+ label={t("L2 budget (per surface)")}+ help={t("Maximum chunks the chunker emits for an L2 update.")}+ value={settings.update.l2_budget}+ onChange={(n) => patch("update", { l2_budget: n })}+ min={1}+ max={200}+ />+ <NumberRow+ label={t("L3 budget (per slot)")}+ help={t("Maximum chunks for an L3 update across the 7 L2 docs.")}+ value={settings.update.l3_budget}+ onChange={(n) => patch("update", { l3_budget: n })}+ min={1}+ max={200}+ />+ </SettingSection>++ <SettingSection+ title={t("Audit mode")}+ description={t(+ "Default LLM rounds for line-level edits against raw evidence.",+ )}+ >+ <NumberRow+ label={t("L2 budget (per surface)")}+ value={settings.audit.l2_budget}+ onChange={(n) => patch("audit", { l2_budget: n })}+ min={1}+ max={200}+ />+ <NumberRow+ label={t("L3 budget (per slot)")}+ value={settings.audit.l3_budget}+ onChange={(n) => patch("audit", { l3_budget: n })}+ min={1}+ max={200}+ />+ </SettingSection>++ <SettingSection+ title={t("Dedup")}+ description={t(+ "Iterative dedup over the full doc. Stops early when an iteration emits zero edits.",+ )}+ >+ <NumberRow+ label={t("Iterations")}+ value={settings.dedup.iterations}+ onChange={(n) => patch("dedup", { iterations: n })}+ min={1}+ max={20}+ />+ <ToggleRow+ label={t("Run dedup automatically after Update")}+ value={settings.dedup.auto_after_update}+ onChange={(v) => patch("dedup", { auto_after_update: v })}+ />+ </SettingSection>++ <SettingSection+ title={t("Merge footnotes")}+ description={t(+ "No-LLM consolidation: collapse duplicate ref rows into one footnote each, then renumber. Idempotent, safe to run any time.",+ )}+ >+ <ToggleRow+ label={t("Merge automatically after Update")}+ value={settings.merge.auto_after_update}+ onChange={(v) => patch("merge", { auto_after_update: v })}+ />+ <ToggleRow+ label={t("Merge automatically after Audit")}+ value={settings.merge.auto_after_audit}+ onChange={(v) => patch("merge", { auto_after_audit: v })}+ />+ <ToggleRow+ label={t("Merge automatically after Dedup")}+ value={settings.merge.auto_after_dedup}+ onChange={(v) => patch("merge", { auto_after_dedup: v })}+ />+ </SettingSection>++ <SettingSection+ title={t("Chunking")}+ description={t("Lower-level knobs that shape how content is split.")}+ >+ <NumberRow+ label={t("Overlap ratio")}+ help={t("Fraction of chunk size carried into the next chunk. 0–0.5.")}+ value={settings.chunking.overlap_ratio}+ onChange={(n) => patch("chunking", { overlap_ratio: n })}+ min={0}+ max={0.5}+ step={0.05}+ isFloat+ />+ <SelectRow+ label={t("Boundary")}+ help={t("Where the chunker prefers to cut.")}+ value={settings.chunking.boundary}+ options={[+ { value: "paragraph", label: t("Paragraph") },+ { value: "sentence", label: t("Sentence") },+ ]}+ onChange={(v) =>+ patch("chunking", { boundary: v as "paragraph" | "sentence" })+ }+ />+ <NumberRow+ label={t("Min chunk chars")}+ help={t("Floor for individual chunk size.")}+ value={settings.chunking.min_chunk_chars}+ onChange={(n) => patch("chunking", { min_chunk_chars: n })}+ min={200}+ max={64000}+ step={100}+ />+ <NumberRow+ label={t("Max chunk chars")}+ help={t("Ceiling for individual chunk size.")}+ value={settings.chunking.max_chunk_chars}+ onChange={(n) => patch("chunking", { max_chunk_chars: n })}+ min={200}+ max={64000}+ step={100}+ />+ </SettingSection>++ <SettingSection+ title={t("References")}+ description={t(+ "How strictly facts must cite the chunk they were extracted from.",+ )}+ >+ <ToggleRow+ label={t("Require ref on every fact")}+ help={t("Drops facts that come back without a ref.")}+ value={settings.reference.enforce_required}+ onChange={(v) => patch("reference", { enforce_required: v })}+ />+ <ToggleRow+ label={t("Drop invalid refs (vs reject the whole fact)")}+ help={t(+ "On: keep the fact, drop only out-of-pool refs. Off: any bad ref rejects the fact.",+ )}+ value={settings.reference.drop_invalid_refs}+ onChange={(v) => patch("reference", { drop_invalid_refs: v })}+ />+ </SettingSection>+ </div>+ );+}++// ── Field components ────────────────────────────────────────────────++interface NumberRowProps {+ label: string;+ help?: string;+ value: number;+ onChange: (n: number) => void;+ min?: number;+ max?: number;+ step?: number;+ isFloat?: boolean;+}++function NumberRow({+ label,+ help,+ value,+ onChange,+ min,+ max,+ step = 1,+ isFloat = false,+}: NumberRowProps) {+ return (+ <SettingRow+ title={label}+ description={help}+ control={+ <input+ type="number"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => {+ const raw = e.target.value;+ if (raw === "") return;+ const n = isFloat ? parseFloat(raw) : parseInt(raw, 10);+ if (!Number.isNaN(n)) onChange(n);+ }}+ className="w-24 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-right text-[12px] outline-none focus:border-[var(--primary)]"+ />+ }+ />+ );+}++interface ToggleRowProps {+ label: string;+ help?: string;+ value: boolean;+ onChange: (v: boolean) => void;+}++function ToggleRow({ label, help, value, onChange }: ToggleRowProps) {+ return (+ <SettingRow+ title={label}+ description={help}+ control={+ <button+ type="button"+ role="switch"+ aria-checked={value}+ onClick={() => onChange(!value)}+ className={+ "relative inline-flex h-5 w-9 items-center rounded-full transition " ++ (value ? "bg-[var(--primary)]" : "bg-[var(--muted)]")+ }+ >+ <span+ className={+ "inline-block h-4 w-4 transform rounded-full bg-white shadow transition " ++ (value ? "translate-x-4" : "translate-x-0.5")+ }+ />+ </button>+ }+ />+ );+}++interface SelectRowProps {+ label: string;+ help?: string;+ value: string;+ options: { value: string; label: string }[];+ onChange: (v: string) => void;+}++function SelectRow({ label, help, value, options, onChange }: SelectRowProps) {+ return (+ <SettingRow+ title={label}+ description={help}+ control={+ <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">+ {options.map((o) => (+ <button+ key={o.value}+ type="button"+ onClick={() => onChange(o.value)}+ className={+ "rounded-md px-2.5 py-1 text-[12px] transition-all " ++ (value === o.value+ ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]")+ }+ >+ {o.label}+ </button>+ ))}+ </div>+ }+ />+ );+}diff --git a/web/features/settings/sections/ModelsSettingsSection.tsx b/web/features/settings/sections/ModelsSettingsSection.tsxnew file mode 100644index 000000000..c4201f17a--- /dev/null+++ b/web/features/settings/sections/ModelsSettingsSection.tsx@@ -0,0 +1,37 @@+"use client";++import { CategoryScroll } from "@/components/settings/CategoryScroll";++import ConnectionsSettingsPage from "./models/ConnectionsSettingsSection";+import LlmSettingsPage from "./models/LlmSettingsSection";+import TaskModelsSettingsPage from "./models/TaskModelsSettingsSection";+import EmbeddingSettingsPage from "./models/EmbeddingSettingsSection";+import SearchSettingsPage from "./models/SearchSettingsSection";+import TtsSettingsPage from "./models/TtsSettingsSection";+import SttSettingsPage from "./models/SttSettingsSection";+import ImageGenSettingsPage from "./models/ImageSettingsSection";+import VideoGenSettingsPage from "./models/VideoSettingsSection";++/**+ * The Models category, in full: every service profile page stacked into one+ * scroll instead of nine routes. `SettingsNav` links each leaf here as+ * `#anchor` rather than a route change, so switching services never remounts+ * this page — see `CategoryScroll`.+ */+export default function ModelsSettingsPage() {+ return (+ <CategoryScroll+ sections={[+ { key: "connections", Component: ConnectionsSettingsPage },+ { key: "llm", Component: LlmSettingsPage },+ { key: "task-models", Component: TaskModelsSettingsPage },+ { key: "embedding", Component: EmbeddingSettingsPage },+ { key: "search", Component: SearchSettingsPage },+ { key: "tts", Component: TtsSettingsPage },+ { key: "stt", Component: SttSettingsPage },+ { key: "imagegen", Component: ImageGenSettingsPage },+ { key: "videogen", Component: VideoGenSettingsPage },+ ]}+ />+ );+}diff --git a/web/features/settings/sections/NetworkSettingsSection.tsx b/web/features/settings/sections/NetworkSettingsSection.tsxnew file mode 100644index 000000000..5fef60da6--- /dev/null+++ b/web/features/settings/sections/NetworkSettingsSection.tsx@@ -0,0 +1,523 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";++import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+ inputClass,+} from "@/components/settings/shared";+import { useSettings } from "@/features/settings/store/SettingsStore";+import {+ DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,+ MAX_CHAT_RESPONSE_TIMEOUT_SECONDS,+ MIN_CHAT_RESPONSE_TIMEOUT_SECONDS,+ clampChatResponseTimeout,+ writeStoredChatResponseTimeout,+} from "@/context/app-shell-storage";+import { apiFetch, apiUrl } from "@/lib/api";+import {+ RuntimeHealthCard,+ TurnCoordinationSettings,+ useRuntimeStatus,+} from "@/features/runtime-status";++type NetworkSettings = {+ backend_port: number;+ frontend_port: number;+ public_api_base: string;+ cors_origins: string[];+};++type NetworkSettingsPayload = {+ settings: NetworkSettings;+ effective: {+ backend_url: string;+ frontend_url: string;+ browser_api_base: string;+ api_base_source: string;+ cors_mode: "explicit" | "permissive";+ cors_origins: string[];+ allow_remote_http_origins: boolean;+ };+ auth: {+ enabled: boolean;+ cookie_secure: boolean;+ cookie_samesite: string;+ cross_site_cookie_ready: boolean;+ };+ restart_required: boolean;+};++function splitOrigins(value: string): string[] {+ return value+ .split(/[,;\n]+/)+ .map((item) => item.trim())+ .filter(Boolean);+}++function normalizeDraft(payload: NetworkSettingsPayload): NetworkSettings {+ return {+ backend_port: payload.settings.backend_port,+ frontend_port: payload.settings.frontend_port,+ public_api_base: payload.settings.public_api_base || "",+ cors_origins: payload.settings.cors_origins || [],+ };+}++function DetailTile({+ label,+ value,+ tone = "neutral",+}: {+ label: string;+ value: string;+ tone?: "neutral" | "ok" | "warn";+}) {+ const dot =+ tone === "ok"+ ? "bg-emerald-500"+ : tone === "warn"+ ? "bg-amber-500"+ : "bg-[var(--border)]";+ return (+ <div className="rounded-xl border border-[var(--border)]/60 bg-[var(--card)] px-4 py-3">+ <div className="flex items-center gap-2 text-[11px] font-medium text-[var(--muted-foreground)]">+ <span className={`h-1.5 w-1.5 rounded-full ${dot}`} />+ {label}+ </div>+ <div+ className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]"+ title={value}+ >+ {value || "-"}+ </div>+ </div>+ );+}++/**+ * Per-user chat idle-timeout control. Self-contained (its own fetch + save via+ * the dedicated ``/settings/chat-response-timeout`` endpoint) and renders+ * independently of the admin network settings below, so any user can adjust it.+ * Mirrors the value to localStorage so the chat watchdog picks it up at once.+ */+function ChatResponseTimeoutSection() {+ const { t } = useTranslation();+ const { registerExtension, pendingExtensionPayload, draftRevision } =+ useSettings();+ const [seconds, setSeconds] = useState<number>(+ DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,+ );+ const [initial, setInitial] = useState<number>(+ DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,+ );+ const [message, setMessage] = useState("");++ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const response = await apiFetch(apiUrl("/api/v1/settings"));+ const data = (await response.json().catch(() => ({}))) as {+ ui?: { chat_response_timeout?: number };+ };+ const value = clampChatResponseTimeout(+ Number(data?.ui?.chat_response_timeout) ||+ DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,+ );+ if (cancelled) return;+ setSeconds(value);+ setInitial(value);+ writeStoredChatResponseTimeout(value);+ } catch {+ // keep the default+ }+ })();+ return () => {+ cancelled = true;+ };+ }, []);++ const dirty = seconds !== initial;++ // Flush through the global Apply (top toolbar) instead of a local button.+ const secondsRef = useRef(seconds);+ secondsRef.current = seconds;+ const save = useCallback(async () => {+ setMessage("");+ try {+ const value = clampChatResponseTimeout(secondsRef.current);+ const response = await apiFetch(+ apiUrl("/api/v1/settings/chat-response-timeout"),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ chat_response_timeout: value }),+ },+ );+ if (!response.ok) throw new Error(t("Failed to save."));+ setSeconds(value);+ setInitial(value);+ writeStoredChatResponseTimeout(value);+ } catch (err) {+ setMessage(err instanceof Error ? err.message : String(err));+ }+ }, [t]);++ useEffect(() => {+ registerExtension("chat-timeout", {+ dirty,+ save,+ payload: { chat_response_timeout: seconds },+ });+ return () => registerExtension("chat-timeout", null);+ }, [dirty, save, seconds, registerExtension]);++ return (+ <SettingSection+ title={t("Chat response timeout")}+ description={t(+ "How long chat waits for a reply before showing a timeout error. Increase it for slow tools like image or video generation.",+ )}+ >+ <SettingRow+ title={t("Timeout (seconds)")}+ description={t(+ "Between {{min}} and {{max}} seconds. Takes effect immediately — no restart.",+ {+ min: MIN_CHAT_RESPONSE_TIMEOUT_SECONDS,+ max: MAX_CHAT_RESPONSE_TIMEOUT_SECONDS,+ },+ )}+ control={+ <input+ className={`${inputClass} w-28`}+ type="number"+ min={MIN_CHAT_RESPONSE_TIMEOUT_SECONDS}+ max={MAX_CHAT_RESPONSE_TIMEOUT_SECONDS}+ value={seconds}+ onChange={(event) => setSeconds(Number(event.target.value))}+ />+ }+ />+ {message && (+ <p className="px-1 pb-3 text-[11.5px] text-[var(--muted-foreground)]">+ {message}+ </p>+ )}+ </SettingSection>+ );+}++export default function NetworkSettingsPage() {+ const { t } = useTranslation();+ const runtime = useRuntimeStatus();+ const { registerExtension, pendingExtensionPayload, draftRevision } =+ useSettings();+ const apiBasePlaceholder = "https://api.example.com";+ const corsPlaceholder = "https://learn.example.com\nhttp://10.0.0.5:3782";+ const [payload, setPayload] = useState<NetworkSettingsPayload | null>(null);+ const [draft, setDraft] = useState<NetworkSettings | null>(null);+ const [corsText, setCorsText] = useState("");+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ async function load() {+ setLoading(true);+ setError(null);+ try {+ const response = await apiFetch(apiUrl("/api/v1/settings/network"));+ const data = (await response.json().catch(() => ({}))) as+ | NetworkSettingsPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in data && data.detail+ ? data.detail+ : t("Failed to load network settings."),+ );+ }+ if (cancelled) return;+ const next = data as NetworkSettingsPayload;+ setPayload(next);+ const pending = pendingExtensionPayload("network") as+ | NetworkSettings+ | undefined;+ const resolved = pending ?? normalizeDraft(next);+ setDraft(resolved);+ setCorsText((resolved.cors_origins || []).join("\n"));+ } catch (err) {+ if (!cancelled) {+ setError(err instanceof Error ? err.message : String(err));+ }+ } finally {+ if (!cancelled) setLoading(false);+ }+ }+ load();+ return () => {+ cancelled = true;+ };+ }, [draftRevision, pendingExtensionPayload, t]);++ const dirty = useMemo(() => {+ if (!payload || !draft) return false;+ const current = normalizeDraft(payload);+ return (+ current.backend_port !== draft.backend_port ||+ current.frontend_port !== draft.frontend_port ||+ current.public_api_base !== draft.public_api_base ||+ JSON.stringify(current.cors_origins) !==+ JSON.stringify(splitOrigins(corsText))+ );+ }, [corsText, draft, payload]);++ // Flush through the global Apply (top toolbar) instead of a local button.+ // Refs keep the registered ``save`` closure reading the latest draft.+ const draftRef = useRef(draft);+ draftRef.current = draft;+ const corsRef = useRef(corsText);+ corsRef.current = corsText;+ const save = useCallback(async () => {+ const current = draftRef.current;+ if (!current) return;+ setError(null);+ try {+ const response = await apiFetch(apiUrl("/api/v1/settings/network"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ ...current,+ cors_origins: splitOrigins(corsRef.current),+ }),+ });+ const data = (await response.json().catch(() => ({}))) as+ | NetworkSettingsPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in data && data.detail+ ? data.detail+ : t("Failed to save network settings."),+ );+ }+ const next = data as NetworkSettingsPayload;+ setPayload(next);+ setDraft(normalizeDraft(next));+ setCorsText((next.settings.cors_origins || []).join("\n"));+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ }, [t]);++ useEffect(() => {+ registerExtension("network", { dirty, save, payload: draft });+ return () => registerExtension("network", null);+ }, [dirty, draft, save, registerExtension]);++ return (+ <div data-tour="tour-network">+ <SettingsPageHeader+ title={t("Network")}+ description={t(+ "Control the browser-facing API URL and CORS origins used by Docker, LAN, and reverse-proxy deployments.",+ )}+ />++ <p className="mb-7 text-[12px] text-[var(--muted-foreground)]">+ {t("Network changes take effect after restart.")}+ </p>++ <div className="mb-7">+ <RuntimeHealthCard+ snapshot={runtime}+ onRefresh={runtime.refresh}+ showDetails+ />+ {runtime.data ? (+ <TurnCoordinationSettings+ value={{+ backendWorkers: runtime.data.workerCount,+ coordinationMode: runtime.data.coordinationMode,+ developmentReload: false,+ leaseTtlSeconds: runtime.data.leaseTtlSeconds,+ recoveryIntervalSeconds: runtime.data.recoveryIntervalSeconds,+ }}+ redisConfigured={runtime.data.redisConfigured}+ />+ ) : null}+ </div>++ <ChatResponseTimeoutSection />++ {loading && (+ <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ {t("Loading network settings...")}+ </div>+ )}++ {!loading && error && (+ <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">+ {error}+ </div>+ )}++ {!loading && payload && draft && (+ <>+ <div className="mb-7 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">+ <DetailTile+ label={t("Browser API")}+ value={payload.effective.browser_api_base}+ tone="ok"+ />+ <DetailTile+ label={t("CORS mode")}+ value={+ payload.effective.cors_mode === "permissive"+ ? t("Permissive until auth is enabled")+ : t("Explicit origins required")+ }+ tone={+ payload.effective.cors_mode === "permissive" ? "ok" : "warn"+ }+ />+ <DetailTile+ label={t("Auth cookie")}+ value={`${payload.auth.cookie_samesite}${+ payload.auth.cookie_secure ? " + Secure" : ""+ }`}+ tone={+ !payload.auth.enabled || payload.auth.cross_site_cookie_ready+ ? "ok"+ : "warn"+ }+ />+ <DetailTile+ label={t("Restart")}+ value={t("Required after save")}+ tone="warn"+ />+ </div>++ <SettingSection+ title={t("Runtime ports")}+ description={t(+ "These ports are read during startup. Docker port mappings must match the container-side values.",+ )}+ >+ <SettingRow+ title={t("Backend port")}+ description={t("FastAPI listens on this port.")}+ control={+ <input+ className={`${inputClass} w-28`}+ type="number"+ min={1}+ max={65535}+ value={draft.backend_port}+ onChange={(event) =>+ setDraft((current) =>+ current+ ? {+ ...current,+ backend_port: Number(event.target.value),+ }+ : current,+ )+ }+ />+ }+ />+ <SettingRow+ title={t("Frontend port")}+ description={t("Next.js serves the Web UI on this port.")}+ control={+ <input+ className={`${inputClass} w-28`}+ type="number"+ min={1}+ max={65535}+ value={draft.frontend_port}+ onChange={(event) =>+ setDraft((current) =>+ current+ ? {+ ...current,+ frontend_port: Number(event.target.value),+ }+ : current,+ )+ }+ />+ }+ />+ </SettingSection>++ <SettingSection+ title={t("Browser API base")}+ description={t(+ "Set this when the browser cannot reach the backend through localhost, such as remote Docker or a reverse proxy.",+ )}+ >+ <SettingRow+ title={t("Public API base")}+ description={t(+ "Leave blank for local Docker. Use the externally reachable backend URL, including any proxy path.",+ )}+ control={+ <input+ className={`${inputClass} w-[360px] max-w-[48vw]`}+ placeholder={apiBasePlaceholder}+ value={draft.public_api_base}+ onChange={(event) =>+ setDraft((current) =>+ current+ ? { ...current, public_api_base: event.target.value }+ : current,+ )+ }+ />+ }+ />+ </SettingSection>++ <SettingSection+ title={t("CORS origins")}+ description={t(+ "Only required for authenticated cross-origin deployments. Use frontend origins, not API URLs.",+ )}+ >+ <div className="py-4">+ <textarea+ className={`${inputClass} min-h-28 resize-y font-mono text-[12.5px] leading-relaxed`}+ placeholder={corsPlaceholder}+ value={corsText}+ onChange={(event) => setCorsText(event.target.value)}+ />+ <p className="mt-2 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Comma, semicolon, and newline separators are accepted. Bare host:port values are stored as http://host:port.",+ )}+ </p>+ </div>+ </SettingSection>++ {payload.auth.enabled && !payload.auth.cookie_secure && (+ <div className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-[12.5px] leading-relaxed text-amber-700 dark:text-amber-300">+ {t(+ "Auth is enabled but secure cookies are off. Cross-site HTTPS deployments should set auth.cookie_secure=true and restart so SameSite=None cookies work in modern browsers.",+ )}+ </div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/web/features/settings/sections/StartersSettingsSection.tsx b/web/features/settings/sections/StartersSettingsSection.tsxnew file mode 100644index 000000000..8b7f8ba23--- /dev/null+++ b/web/features/settings/sections/StartersSettingsSection.tsx@@ -0,0 +1,193 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import Link from "next/link";+import { ArrowUpRight, Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";++import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+ inputClass,+} from "@/components/settings/shared";+import { useSettings } from "@/features/settings/store/SettingsStore";+import { apiFetch, apiUrl } from "@/lib/api";+import { EXTENSION_ENDPOINTS } from "@/lib/settings-extensions";++type StarterSettings = { trace_count: number };++type StarterSettingsPayload = {+ settings: StarterSettings;+ bounds: { trace_count: [number, number] };+};++export default function StarterSettingsPage() {+ const { t } = useTranslation();+ const { registerExtension, pendingExtensionPayload, draftRevision } =+ useSettings();+ const [payload, setPayload] = useState<StarterSettingsPayload | null>(null);+ const [draft, setDraft] = useState<StarterSettings | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ async function load() {+ setLoading(true);+ setError(null);+ try {+ const response = await apiFetch(+ apiUrl(EXTENSION_ENDPOINTS["chat-starters"]),+ );+ const data = (await response.json().catch(() => ({}))) as+ | StarterSettingsPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in data && data.detail+ ? String(data.detail)+ : t("Failed to load starter settings."),+ );+ }+ if (cancelled) return;+ const next = data as StarterSettingsPayload;+ setPayload(next);+ // An edit left behind earlier in this session (or parked in a saved+ // draft) wins over the server value — leaving the page is not a way+ // to discard changes.+ const pending = pendingExtensionPayload("chat-starters") as+ | StarterSettings+ | undefined;+ setDraft(pending ? { ...pending } : { ...next.settings });+ } catch (err) {+ if (!cancelled)+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ if (!cancelled) setLoading(false);+ }+ }+ load();+ return () => {+ cancelled = true;+ };+ }, [draftRevision, pendingExtensionPayload, t]);++ const dirty = useMemo(+ () =>+ Boolean(+ payload && draft && payload.settings.trace_count !== draft.trace_count,+ ),+ [draft, payload],+ );++ // Flush through the global Apply (top toolbar) instead of a local button.+ const draftRef = useRef(draft);+ draftRef.current = draft;+ const save = useCallback(async () => {+ const current = draftRef.current;+ if (!current) return;+ setError(null);+ try {+ const response = await apiFetch(+ apiUrl(EXTENSION_ENDPOINTS["chat-starters"]),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(current),+ },+ );+ const data = (await response.json().catch(() => ({}))) as+ | StarterSettingsPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in data && data.detail+ ? String(data.detail)+ : t("Failed to save starter settings."),+ );+ }+ const next = data as StarterSettingsPayload;+ setPayload(next);+ setDraft({ ...next.settings });+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ }, [t]);++ useEffect(() => {+ registerExtension("chat-starters", { dirty, save, payload: draft });+ return () => registerExtension("chat-starters", null);+ }, [dirty, draft, save, registerExtension]);++ const bounds = payload?.bounds.trace_count;++ return (+ <div>+ <SettingsPageHeader+ title={t("Starting points")}+ description={t(+ "The three lines under the composer on an empty home screen, generated from your long-term memory and what you have been working on lately.",+ )}+ />++ {loading && (+ <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ {t("Loading starter settings...")}+ </div>+ )}++ {!loading && error && (+ <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">+ {error}+ </div>+ )}++ {!loading && payload && draft && (+ <SettingSection+ title={t("Material")}+ description={t(+ "Your consolidated memory is always included. This controls how much raw recent activity goes with it — conversations, practice questions, searches, documents, in one list ordered by time.",+ )}+ >+ <SettingRow+ title={t("Recent activities")}+ description={t(+ "More gives the model a longer view of what you have touched; fewer keeps it focused on this week. Takes effect the next time the lines are regenerated.",+ )}+ control={+ <input+ className={`${inputClass} w-28`}+ type="number"+ min={bounds?.[0] ?? 3}+ max={bounds?.[1] ?? 100}+ value={draft.trace_count}+ onChange={(event) =>+ setDraft((current) =>+ current+ ? { ...current, trace_count: Number(event.target.value) }+ : current,+ )+ }+ />+ }+ />+ </SettingSection>+ )}++ {!loading && payload && (+ <p className="mt-5 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t("These lines are written by the active model unless you pin one.")}{" "}+ <Link+ href="/settings/models#task-models"+ className="inline-flex items-center gap-1 text-[var(--foreground)] underline-offset-2 hover:underline"+ >+ {t("Task models")}+ <ArrowUpRight className="h-3 w-3" />+ </Link>+ </p>+ )}+ </div>+ );+}diff --git a/web/features/settings/sections/ToolsSettingsSection.tsx b/web/features/settings/sections/ToolsSettingsSection.tsxnew file mode 100644index 000000000..8cb3b6554--- /dev/null+++ b/web/features/settings/sections/ToolsSettingsSection.tsx@@ -0,0 +1,611 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { ChevronDown, Loader2, Lock, Search, Wrench, X } from "lucide-react";+import Link from "next/link";+import { useTranslation } from "react-i18next";++import { useSettings } from "@/features/settings/store/SettingsStore";+import { SettingsPageHeader } from "@/components/settings/shared";+import { apiFetch, apiUrl } from "@/lib/api";+import { invalidateEnabledOptionalToolsCache } from "@/lib/tools-settings";+import {+ toolAvailabilityCopy,+ toolEffectiveEnabled,+} from "@/lib/tool-availability";++type ToolParameter = {+ name: string;+ type: string;+ description: string;+ required: boolean;+ default: unknown;+ enum: string[] | null;+};++type ToolHints = {+ short_description: string;+ when_to_use: string;+ input_format: string;+ guideline: string;+ note: string;+ phase: string;+ aliases: { name: string; description: string; phase: string }[];+};++type BuiltinTool = {+ name: string;+ description: string;+ parameters: ToolParameter[];+ hints: { en: ToolHints; zh: ToolHints };+ aliases: string[];+ toggleable: boolean;+ enabled: boolean;+ // ``coming_soon`` tools are listed for visibility but the chat agent+ // cannot invoke them. The settings UI surfaces them with a locked-off+ // toggle and a "Coming soon" badge.+ coming_soon?: boolean;+ // The capability that owns this tool (e.g. "solve" / "mastery"), or null+ // for a plain system built-in. Owned tools render in their own section+ // below the built-in tools.+ capability?: string | null;+ // Runtime readiness is independent of the saved composer preference.+ available?: boolean;+ unavailable_reason?: string | null;+};++type ToolsResponse = {+ tools: BuiltinTool[];+ enabled_optional_tools: string[];+};++type ToolSection = {+ key: string;+ label: string;+ hint: string;+ tools: BuiltinTool[];+};++// Display labels for capability-owned tool sections, keyed by the backend's+// capability id. Falls back to the raw id for any unmapped capability.+const CAPABILITY_LABELS: Record<string, { zh: string; en: string }> = {+ solve: { zh: "深度解题", en: "Deep Solve" },+ mastery: { zh: "精通路径", en: "Mastery Path" },+};++export default function ToolsSettingsPage() {+ const { t } = useTranslation();+ const { language } = useSettings();+ const [tools, setTools] = useState<BuiltinTool[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [expanded, setExpanded] = useState<Set<string>>(new Set());+ const [enabled, setEnabled] = useState<Set<string>>(new Set());+ const [pending, setPending] = useState<Set<string>>(new Set());+ const [saveError, setSaveError] = useState<string | null>(null);+ const [query, setQuery] = useState("");++ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const res = await apiFetch(apiUrl("/api/v1/tools"));+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const payload = (await res.json()) as ToolsResponse;+ if (!cancelled) {+ setTools(payload.tools);+ setEnabled(new Set(payload.enabled_optional_tools ?? []));+ }+ } catch (err) {+ if (!cancelled) {+ setError(err instanceof Error ? err.message : String(err));+ }+ }+ })();+ return () => {+ cancelled = true;+ };+ }, []);++ const persist = useCallback(async (next: Set<string>) => {+ const body = JSON.stringify({ enabled_tools: Array.from(next) });+ const res = await apiFetch(apiUrl("/api/v1/settings/enabled-tools"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body,+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const payload = (await res.json()) as { enabled_optional_tools: string[] };+ // Bust the cached snapshot any other page in this tab is holding.+ invalidateEnabledOptionalToolsCache();+ return new Set(payload.enabled_optional_tools);+ }, []);++ const handleToggleEnabled = useCallback(+ async (toolName: string) => {+ if (pending.has(toolName)) return;+ const before = enabled;+ const next = new Set(before);+ if (next.has(toolName)) next.delete(toolName);+ else next.add(toolName);+ setEnabled(next);+ setPending((prev) => new Set(prev).add(toolName));+ setSaveError(null);+ try {+ const saved = await persist(next);+ setEnabled(saved);+ } catch (err) {+ setEnabled(before);+ setSaveError(err instanceof Error ? err.message : String(err));+ } finally {+ setPending((prev) => {+ const out = new Set(prev);+ out.delete(toolName);+ return out;+ });+ }+ },+ [enabled, pending, persist],+ );++ const sections = useMemo<ToolSection[] | null>(() => {+ if (!tools) return null;+ const zh = language === "zh";+ // Buckets: toggleable (体验增强) first, then locked-on built-ins, then one+ // section per capability for its owned tools. Backend order is preserved+ // within each bucket (mirrors USER_TOGGLEABLE_TOOL_NAMES / the+ // BUILTIN_TOOL_TYPES registration order). Coming-soon tools share the+ // toggleable bucket — same concept, just temporarily unavailable.+ const experience: BuiltinTool[] = [];+ const builtin: BuiltinTool[] = [];+ const capabilities = new Map<string, BuiltinTool[]>();+ for (const tool of tools) {+ if (tool.capability) {+ const list = capabilities.get(tool.capability) ?? [];+ list.push(tool);+ capabilities.set(tool.capability, list);+ } else if (tool.coming_soon) {+ experience.push(tool);+ } else {+ (tool.toggleable ? experience : builtin).push(tool);+ }+ }+ const out: ToolSection[] = [];+ if (experience.length) {+ out.push({+ key: "experience",+ label: zh ? "体验增强" : "Experience Enhancement",+ hint: zh+ ? "用户可选;按需为 chat agent 开启或关闭。"+ : "User-toggleable. Switch on or off to shape the chat agent's behavior.",+ tools: experience,+ });+ }+ if (builtin.length) {+ out.push({+ key: "builtin",+ label: zh ? "内置工具" : "Built-in Tools",+ hint: zh+ ? "Chat agent 在需要时自动挂载,无需手动开关。"+ : "Mounted automatically by the chat agent when needed. Not user-toggleable.",+ tools: builtin,+ });+ }+ for (const [cap, list] of capabilities) {+ const label = CAPABILITY_LABELS[cap]?.[zh ? "zh" : "en"] ?? cap;+ out.push({+ key: `cap:${cap}`,+ label: zh ? `${label} · 能力工具` : `${label} · Capability Tools`,+ hint: zh+ ? "该能力的专属工具,仅在此能力运行时挂载。"+ : "Tools specific to this capability; mounted only when it runs.",+ tools: list,+ });+ }+ return out;+ }, [tools, language]);++ const filteredSections = useMemo<ToolSection[] | null>(() => {+ if (!sections) return null;+ const needle = query.trim().toLocaleLowerCase();+ if (!needle) return sections;++ return sections+ .map((section) => ({+ ...section,+ tools: section.tools.filter((tool) => {+ const hints = tool.hints[language];+ const alternateHints = tool.hints[language === "zh" ? "en" : "zh"];+ const searchableText = [+ tool.name,+ tool.description,+ ...tool.aliases,+ hints.short_description,+ hints.when_to_use,+ hints.input_format,+ hints.guideline,+ hints.note,+ ...hints.aliases.flatMap((alias) => [+ alias.name,+ alias.description,+ alias.phase,+ ]),+ alternateHints.short_description,+ alternateHints.when_to_use,+ alternateHints.input_format,+ alternateHints.guideline,+ alternateHints.note,+ ...tool.parameters.flatMap((parameter) => [+ parameter.name,+ parameter.type,+ parameter.description,+ ...(parameter.enum ?? []),+ ]),+ ]+ .filter(Boolean)+ .join(" ")+ .toLocaleLowerCase();+ return searchableText.includes(needle);+ }),+ }))+ .filter((section) => section.tools.length > 0);+ }, [language, query, sections]);++ const toggleExpanded = (name: string) => {+ setExpanded((prev) => {+ const next = new Set(prev);+ if (next.has(name)) next.delete(name);+ else next.add(name);+ return next;+ });+ };++ return (+ <div data-tour="tour-tools">+ <SettingsPageHeader+ title={t("Tools")}+ description={t(+ "Switch user-toggleable tools on or off. Locked tools are mounted automatically when the chat agent needs them.",+ )}+ />++ <div className="mb-8">+ <label className="sr-only" htmlFor="tools-search">+ {t("Search tools")}+ </label>+ <div className="relative">+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />+ <input+ id="tools-search"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t("Search tools")}+ aria-label={t("Search tools")}+ className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-10 pr-10 text-[13px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)]/60 focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/20"+ spellCheck={false}+ />+ {query && (+ <button+ type="button"+ onClick={() => setQuery("")}+ aria-label={t("Clear")}+ title={t("Clear")}+ className="absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)] focus:outline-none focus:ring-2 focus:ring-[var(--ring)]/30"+ >+ <X className="h-3.5 w-3.5" />+ </button>+ )}+ </div>+ </div>++ {error && (+ <div className="rounded-xl border border-red-500/40 bg-red-500/5 px-4 py-3 text-[12px] text-red-500">+ {t("Failed to load tools")}: {error}+ </div>+ )}++ {saveError && (+ <div className="mb-4 rounded-xl border border-red-500/40 bg-red-500/5 px-4 py-3 text-[12px] text-red-500">+ {t("Failed to save")}: {saveError}+ </div>+ )}++ {!tools && !error && (+ <div className="flex items-center gap-2 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("Loading...")}+ </div>+ )}++ {filteredSections && query.trim() && filteredSections.length === 0 && (+ <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-8 text-center text-[12.5px] text-[var(--muted-foreground)]">+ {t('No tools match “{{query}}”.', { query: query.trim() })}+ </div>+ )}++ {filteredSections && filteredSections.length > 0 && (+ <div className="space-y-8">+ {filteredSections.map((section) => {+ const list = section.tools;+ if (list.length === 0) return null;+ return (+ <section key={section.key}>+ <header className="mb-3 flex items-baseline justify-between gap-3">+ <div className="min-w-0">+ <h2 className="text-[14px] font-semibold tracking-tight text-[var(--foreground)]">+ {section.label}+ </h2>+ <p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">+ {section.hint}+ </p>+ </div>+ <span className="shrink-0 text-[11px] text-[var(--muted-foreground)]">+ {list.length}+ </span>+ </header>+ <div className="border-t border-[var(--border)]/60">+ {list.map((tool, idx) => {+ const isOpen = expanded.has(tool.name);+ const hints = tool.hints[language];+ const isPending = pending.has(tool.name);+ const isComingSoon = !!tool.coming_soon;+ const isAvailable = tool.available !== false;+ const availability = !isAvailable+ ? toolAvailabilityCopy(+ tool.unavailable_reason,+ language === "zh" ? "zh" : "en",+ )+ : null;+ const isEnabled = toolEffectiveEnabled(+ tool.toggleable ? enabled.has(tool.name) : true,+ isAvailable,+ isComingSoon,+ );+ return (+ <div+ key={tool.name}+ className={+ idx > 0+ ? "border-t border-[var(--border)]/50"+ : undefined+ }+ >+ <div className="flex w-full items-start gap-3 px-5 py-4">+ <Wrench+ className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${+ isComingSoon || !isAvailable+ ? "text-[var(--muted-foreground)]/40"+ : "text-[var(--muted-foreground)]"+ }`}+ />+ <button+ type="button"+ onClick={() => toggleExpanded(tool.name)}+ className="flex min-w-0 flex-1 items-start gap-3 text-left"+ aria-expanded={isOpen}+ >+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span+ className={`font-mono text-[13px] font-medium ${+ isComingSoon+ ? "text-[var(--foreground)]/60"+ : "text-[var(--foreground)]"+ }`}+ >+ {tool.name}+ </span>+ {tool.aliases.length > 0 && (+ <span className="text-[10.5px] text-[var(--muted-foreground)]/70">+ {tool.aliases.join(" · ")}+ </span>+ )}+ {isComingSoon && (+ <span className="inline-flex items-center gap-1 rounded-full border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {language === "zh"+ ? "敬请期待"+ : "Coming soon"}+ </span>+ )}+ {availability && !isComingSoon && (+ <span className="inline-flex items-center rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300">+ {availability.badge}+ </span>+ )}+ </div>+ <p+ className={`mt-1 text-[12.5px] leading-relaxed ${+ isComingSoon+ ? "text-[var(--muted-foreground)]/70"+ : "text-[var(--muted-foreground)]"+ }`}+ >+ {hints.short_description || tool.description}+ </p>+ {availability && !isComingSoon && (+ <p className="mt-1 text-[11.5px] leading-relaxed text-amber-700 dark:text-amber-300">+ {availability.detail}{" "}+ {availability.href && (+ <Link+ href={availability.href}+ className="font-medium underline underline-offset-2"+ >+ {language === "zh" ? "打开设置" : "Open settings"}+ </Link>+ )}+ </p>+ )}+ </div>+ <ChevronDown+ className={`mt-1 h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition-transform ${+ isOpen ? "rotate-180" : ""+ }`}+ />+ </button>+ <div className="mt-0.5 flex shrink-0 items-center gap-2">+ {isComingSoon ? (+ <ToolToggle+ checked={false}+ disabled+ onChange={() => {+ /* locked */+ }}+ label={+ language === "zh" ? "敬请期待" : "Coming soon"+ }+ />+ ) : !isAvailable ? (+ <ToolToggle+ checked={false}+ disabled+ onChange={() => {+ /* runtime unavailable */+ }}+ label={availability?.badge ?? t("Not configured")}+ />+ ) : tool.toggleable ? (+ <ToolToggle+ checked={isEnabled}+ disabled={isPending}+ onChange={() => handleToggleEnabled(tool.name)}+ label={t(isEnabled ? "On" : "Off")}+ />+ ) : (+ <span+ className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)]/40 px-2 py-0.5 text-[10.5px] text-[var(--muted-foreground)]"+ title={t(+ "Auto-mounted by the agent when needed. Not user-toggleable.",+ )}+ >+ <Lock className="h-3 w-3" />+ {t("Always on")}+ </span>+ )}+ </div>+ </div>+ {isOpen && (+ <div className="space-y-4 border-t border-[var(--border)]/40 bg-[var(--background)]/40 px-5 py-4 text-[12.5px] leading-relaxed">+ {hints.when_to_use && (+ <Field+ label={t("When to use")}+ body={hints.when_to_use}+ />+ )}+ {hints.input_format && (+ <Field+ label={t("Input format")}+ body={hints.input_format}+ mono+ />+ )}+ {hints.guideline && (+ <Field+ label={t("Guideline")}+ body={hints.guideline}+ />+ )}+ {hints.note && (+ <Field label={t("Note")} body={hints.note} />+ )}+ {tool.parameters.length > 0 && (+ <div>+ <div className="mb-1 text-[10.5px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]/80">+ {t("Parameters")}+ </div>+ <ul className="space-y-1.5">+ {tool.parameters.map((p) => (+ <li+ key={p.name}+ className="flex items-baseline gap-2"+ >+ <span className="font-mono text-[12px] text-[var(--foreground)]">+ {p.name}+ </span>+ <span className="text-[10.5px] text-[var(--muted-foreground)]/70">+ {p.type}+ {p.required+ ? ""+ : ` · ${t("optional")}`}+ </span>+ {p.description && (+ <span className="text-[12px] text-[var(--muted-foreground)]">+ — {p.description}+ </span>+ )}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ </section>+ );+ })}+ </div>+ )}+ </div>+ );+}++function ToolToggle({+ checked,+ disabled,+ onChange,+ label,+}: {+ checked: boolean;+ disabled: boolean;+ onChange: () => void;+ label: string;+}) {+ return (+ <button+ type="button"+ role="switch"+ aria-checked={checked}+ aria-label={label}+ disabled={disabled}+ onClick={onChange}+ className={`relative inline-flex h-[18px] w-[32px] shrink-0 items-center rounded-full border transition-colors ${+ checked+ ? "border-[var(--primary)] bg-[var(--primary)]/70"+ : "border-[var(--border)] bg-[var(--muted)]/50"+ } ${disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer"}`}+ >+ <span+ className={`inline-block h-[12px] w-[12px] transform rounded-full bg-white shadow transition-transform ${+ checked ? "translate-x-[16px]" : "translate-x-[2px]"+ }`}+ />+ </button>+ );+}++function Field({+ label,+ body,+ mono,+}: {+ label: string;+ body: string;+ mono?: boolean;+}) {+ return (+ <div>+ <div className="mb-1 text-[10.5px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]/80">+ {label}+ </div>+ <p+ className={`whitespace-pre-wrap text-[12.5px] leading-relaxed text-[var(--foreground)]/90 ${+ mono ? "font-mono" : ""+ }`}+ >+ {body}+ </p>+ </div>+ );+}diff --git a/web/features/settings/sections/VideoLearningSettingsSection.tsx b/web/features/settings/sections/VideoLearningSettingsSection.tsxnew file mode 100644index 000000000..21ed01e12--- /dev/null+++ b/web/features/settings/sections/VideoLearningSettingsSection.tsx@@ -0,0 +1,235 @@+"use client";++import { useEffect, useState } from "react";+import { CheckCircle2, Loader2, Save, Server, Youtube } from "lucide-react";+import { useTranslation } from "react-i18next";++import { SettingsPageHeader } from "@/components/settings/shared";+import {+ getVideoLearningSettings,+ saveVideoLearningSettings,+ testInvidious,+ type VideoLearningSettings,+} from "@/lib/video-learning-api";++const DEFAULTS: VideoLearningSettings = {+ version: 1,+ default_provider: "youtube",+ youtube: { transcript_provider: "youtube_transcript_api" },+ invidious: { api_base_url: "", public_base_url: "" },+};++export default function VideoLearningSettingsPage() {+ const { t } = useTranslation();+ const [settings, setSettings] = useState(DEFAULTS);+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [message, setMessage] = useState("");++ useEffect(() => {+ void getVideoLearningSettings()+ .then(setSettings)+ .catch((error) =>+ setMessage(+ error instanceof Error+ ? error.message+ : t("Settings could not be loaded."),+ ),+ )+ .finally(() => setLoading(false));+ }, [t]);++ const save = async () => {+ setSaving(true);+ setMessage("");+ try {+ setSettings(await saveVideoLearningSettings(settings));+ setMessage(+ t("Saved. New and reopened videos use this provider immediately."),+ );+ } catch (error) {+ setMessage(+ error instanceof Error+ ? error.message+ : t("Settings could not be saved."),+ );+ } finally {+ setSaving(false);+ }+ };++ const test = async () => {+ setMessage(t("Testing Invidious…"));+ try {+ const result = await testInvidious(settings);+ setMessage(+ result.ok+ ? t("Invidious connected ({{message}}).", result)+ : t("Invidious unavailable: {{message}}", result),+ );+ } catch (error) {+ setMessage(+ error instanceof Error ? error.message : t("Connection test failed."),+ );+ }+ };++ return (+ <div className="space-y-6">+ <SettingsPageHeader+ title={t("Video Learning")}+ description={t(+ "Choose native YouTube or a self-hosted Invidious instance. Provider changes do not rebuild learning materials or reset progress.",+ )}+ />+ {loading ? (+ <Loader2 className="h-5 w-5 animate-spin" />+ ) : (+ <>+ <div className="grid gap-3 sm:grid-cols-2">+ {(+ [+ [+ "youtube",+ Youtube,+ t(+ "Official privacy-enhanced IFrame Player. No media is proxied or stored.",+ ),+ ],+ [+ "invidious",+ Server,+ t(+ "HTML5 playback through your configured Invidious instance.",+ ),+ ],+ ] as const+ ).map(([provider, Icon, description]) => (+ <button+ key={provider}+ type="button"+ onClick={() =>+ setSettings((current) => ({+ ...current,+ default_provider: provider,+ }))+ }+ className={`rounded-xl border p-4 text-left ${settings.default_provider === provider ? "border-[var(--primary)] ring-1 ring-[var(--primary)]" : "border-[var(--border)]"}`}+ >+ <div className="flex items-center gap-2 font-medium">+ <Icon className="h-5 w-5" />+ {provider === "youtube"+ ? t("Native YouTube")+ : t("Self-hosted Invidious")}+ </div>+ <p className="mt-2 text-sm text-[var(--muted-foreground)]">+ {description}+ </p>+ </button>+ ))}+ </div>++ <div className="space-y-4 rounded-xl border border-[var(--border)] p-5">+ <h3 className="font-medium">{t("Invidious connection")}</h3>+ <label className="block text-sm">+ <span className="mb-1 block">{t("Backend API origin")}</span>+ <input+ value={settings.invidious.api_base_url}+ onChange={(event) =>+ setSettings((current) => ({+ ...current,+ invidious: {+ ...current.invidious,+ api_base_url: event.target.value,+ },+ }))+ }+ placeholder={t("Invidious API URL")}+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono"+ />+ </label>+ <label className="block text-sm">+ <span className="mb-1 block">+ {t("Browser-facing origin (optional)")}+ </span>+ <input+ value={settings.invidious.public_base_url}+ onChange={(event) =>+ setSettings((current) => ({+ ...current,+ invidious: {+ ...current.invidious,+ public_base_url: event.target.value,+ },+ }))+ }+ placeholder={t("Defaults to the API origin")}+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono"+ />+ </label>+ <button+ type="button"+ onClick={() => void test()}+ className="rounded-lg border border-[var(--border)] px-3 py-2 text-sm"+ >+ {t("Test connection")}+ </button>+ </div>++ <label className="flex items-center justify-between gap-4 rounded-xl border border-[var(--border)] p-4 text-sm">+ <span>+ <strong>{t("YouTube transcript adapter")}</strong>+ <br />+ <span className="text-[var(--muted-foreground)]">+ {t(+ "Optional captions; playback remains available when the package or captions are unavailable.",+ )}+ </span>+ </span>+ <select+ value={settings.youtube.transcript_provider}+ onChange={(event) =>+ setSettings((current) => ({+ ...current,+ youtube: {+ transcript_provider: event.target.value as+ | "youtube_transcript_api"+ | "none",+ },+ }))+ }+ className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-2"+ >+ <option value="youtube_transcript_api">+ {t("youtube-transcript-api")}+ </option>+ <option value="none">{t("Disabled")}</option>+ </select>+ </label>++ <div className="flex items-center gap-3">+ <button+ type="button"+ onClick={() => void save()}+ disabled={saving}+ className="inline-flex items-center gap-2 rounded-lg bg-[var(--foreground)] px-4 py-2 text-sm text-[var(--background)] disabled:opacity-50"+ >+ {saving ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Save className="h-4 w-4" />+ )}{" "}+ {t("Save")}+ </button>+ {message && (+ <p className="inline-flex items-center gap-1 text-sm text-[var(--muted-foreground)]">+ <CheckCircle2 className="h-4 w-4" />+ {message}+ </p>+ )}+ </div>+ </>+ )}+ </div>+ );+}diff --git a/web/features/settings/sections/models/ConnectionsSettingsSection.tsx b/web/features/settings/sections/models/ConnectionsSettingsSection.tsxnew file mode 100644index 000000000..b13545199--- /dev/null+++ b/web/features/settings/sections/models/ConnectionsSettingsSection.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { ConnectionsEditor } from "@/components/settings/ConnectionsEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function ConnectionsSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Connections")}+ description={t(+ "One vendor credential, supplying every model service that can use it. Services can still hold their own key instead.",+ )}+ />+ <ConnectionsEditor />+ </div>+ );+}diff --git a/web/features/settings/sections/models/EmbeddingSettingsSection.tsx b/web/features/settings/sections/models/EmbeddingSettingsSection.tsxnew file mode 100644index 000000000..71a59b96a--- /dev/null+++ b/web/features/settings/sections/models/EmbeddingSettingsSection.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function EmbeddingSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Embedding")}+ description={t(+ "Configure embedding model profiles. Used by retrieval and knowledge-base ingestion.",+ )}+ />+ <ServiceConfigEditor service="embedding" />+ </div>+ );+}diff --git a/web/features/settings/sections/models/ImageSettingsSection.tsx b/web/features/settings/sections/models/ImageSettingsSection.tsxnew file mode 100644index 000000000..b5a92c9b2--- /dev/null+++ b/web/features/settings/sections/models/ImageSettingsSection.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function ImageGenSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Image Generation")}+ description={t(+ "Text-to-image model used by the chat 'imagegen' tool. Works with any OpenAI-compatible /images/generations API — OpenAI, Volcengine Seedream, or compatible gateways.",+ )}+ />+ <ServiceConfigEditor service="imagegen" />+ </div>+ );+}diff --git a/web/features/settings/sections/models/LlmSettingsSection.tsx b/web/features/settings/sections/models/LlmSettingsSection.tsxnew file mode 100644index 000000000..b7aacbde5--- /dev/null+++ b/web/features/settings/sections/models/LlmSettingsSection.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function LlmSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("LLM")}+ description={t(+ "Configure language model profiles. The active model is used for chat and most agent reasoning.",+ )}+ />+ <ServiceConfigEditor service="llm" />+ </div>+ );+}diff --git a/web/features/settings/sections/models/SearchSettingsSection.tsx b/web/features/settings/sections/models/SearchSettingsSection.tsxnew file mode 100644index 000000000..87376856d--- /dev/null+++ b/web/features/settings/sections/models/SearchSettingsSection.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function SearchSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Search")}+ description={t(+ "Configure web search providers. Used by the web_search tool and any agent step that hits the open web.",+ )}+ />+ <ServiceConfigEditor service="search" />+ </div>+ );+}diff --git a/web/features/settings/sections/models/SttSettingsSection.tsx b/web/features/settings/sections/models/SttSettingsSection.tsxnew file mode 100644index 000000000..3db2f250b--- /dev/null+++ b/web/features/settings/sections/models/SttSettingsSection.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function SttSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Speech-to-Text")}+ description={t(+ "Transcribe the chat composer's microphone recordings. Works with any OpenAI-compatible audio API — OpenAI, Groq, SiliconFlow, Azure, or a local server.",+ )}+ />+ <ServiceConfigEditor service="stt" />+ </div>+ );+}diff --git a/web/features/settings/sections/models/TaskModelsSettingsSection.tsx b/web/features/settings/sections/models/TaskModelsSettingsSection.tsxnew file mode 100644index 000000000..cb7b5f304--- /dev/null+++ b/web/features/settings/sections/models/TaskModelsSettingsSection.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { TaskModelsEditor } from "@/components/settings/TaskModelsEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function TaskModelsSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Task models")}+ description={t(+ "Conversation titles and home screen starting points. Configured like the LLM — pick a provider, then a model. Left empty, both use the LLM.",+ )}+ />+ <TaskModelsEditor />+ </div>+ );+}diff --git a/web/features/settings/sections/models/TtsSettingsSection.tsx b/web/features/settings/sections/models/TtsSettingsSection.tsxnew file mode 100644index 000000000..454f9d4d6--- /dev/null+++ b/web/features/settings/sections/models/TtsSettingsSection.tsx@@ -0,0 +1,71 @@+"use client";++import { useTranslation } from "react-i18next";++import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";+import { SettingsPageHeader } from "@/components/settings/shared";+import { useVoiceAutoplayPreference } from "@/hooks/useVoiceAutoplay";++function AutoplayToggle() {+ const { t } = useTranslation();+ const { value, setValue, loading } = useVoiceAutoplayPreference();+ return (+ <div className="flex items-start justify-between gap-6 border-y border-[var(--border)]/50 py-3.5">+ <div className="min-w-0 flex-1">+ <div className="text-[13.5px] font-medium text-[var(--foreground)]">+ {t("Auto-play replies")}+ </div>+ <p className="mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Read each assistant reply aloud automatically. You can also toggle this per conversation from the speaker button.",+ )}+ </p>+ </div>+ <button+ type="button"+ role="switch"+ aria-checked={value}+ disabled={loading}+ onClick={() => setValue(!value)}+ className={`relative mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors disabled:opacity-50 ${+ value ? "bg-[var(--foreground)]" : "bg-[var(--border)]"+ }`}+ aria-label={t("Auto-play replies")}+ >+ <span+ className={`inline-block h-4 w-4 transform rounded-full bg-[var(--background)] shadow-sm transition-transform ${+ value ? "translate-x-4" : "translate-x-0.5"+ }`}+ />+ </button>+ </div>+ );+}++export default function TtsSettingsPage() {+ const { t } = useTranslation();+ return (+ <div className="space-y-10">+ <SettingsPageHeader+ title={t("Text-to-Speech")}+ description={t(+ "Read assistant replies aloud from the chat speaker button. Works with any OpenAI-compatible audio API — OpenAI, OpenRouter, Groq, SiliconFlow, Azure, or a local server.",+ )}+ />++ <ServiceConfigEditor service="tts" />++ <section>+ <div className="mb-3">+ <h2 className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">+ {t("Playback")}+ </h2>+ <p className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t("How spoken replies behave in chat.")}+ </p>+ </div>+ <AutoplayToggle />+ </section>+ </div>+ );+}diff --git a/web/features/settings/sections/models/VideoSettingsSection.tsx b/web/features/settings/sections/models/VideoSettingsSection.tsxnew file mode 100644index 000000000..6fd2ca136--- /dev/null+++ b/web/features/settings/sections/models/VideoSettingsSection.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { ServiceConfigEditor } from "@/components/settings/ServiceConfigEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function VideoGenSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Video Generation")}+ description={t(+ "Text-to-video model used by the chat 'videogen' tool. Rendering is asynchronous and may take a minute or more. Uses async task providers like Volcengine Seedance.",+ )}+ />+ <ServiceConfigEditor service="videogen" />+ </div>+ );+}diff --git a/web/features/settings/store/ModelCatalogProvider.tsx b/web/features/settings/store/ModelCatalogProvider.tsxnew file mode 100644index 000000000..e04b03210--- /dev/null+++ b/web/features/settings/store/ModelCatalogProvider.tsx@@ -0,0 +1,99 @@+"use client";++import { createContext, useContext, useMemo, type ReactNode } from "react";+import { useSettings, type SettingsContextValue } from "./SettingsStore";++type ModelCatalogSlice = Pick<+ SettingsContextValue,+ | "catalog"+ | "draft"+ | "providers"+ | "catalogEditable"+ | "mutateCatalog"+ | "addProfile"+ | "removeActiveProfile"+ | "addModel"+ | "removeActiveModel"+ | "updateProfileField"+ | "updateModelField"+ | "updateModelBoolField"+ | "updateContextWindowField"+ | "updateReasoningEffort"+ | "connectionTargets"+ | "connectionTarget"+ | "addConnection"+ | "updateConnectionField"+ | "removeConnection"+ | "unlinkProfile"+ | "linkConnectionToServices"+ | "llmContextDetection"+ | "applyDetectedContextWindow"+ | "embeddingCapabilities"+ | "embeddingDefaultDim"+>;++const ModelCatalogContext = createContext<ModelCatalogSlice | null>(null);++export function ModelCatalogProvider({ children }: { children: ReactNode }) {+ const source = useSettings();+ const value = useMemo<ModelCatalogSlice>(() => ({+ catalog: source.catalog,+ draft: source.draft,+ providers: source.providers,+ catalogEditable: source.catalogEditable,+ mutateCatalog: source.mutateCatalog,+ addProfile: source.addProfile,+ removeActiveProfile: source.removeActiveProfile,+ addModel: source.addModel,+ removeActiveModel: source.removeActiveModel,+ updateProfileField: source.updateProfileField,+ updateModelField: source.updateModelField,+ updateModelBoolField: source.updateModelBoolField,+ updateContextWindowField: source.updateContextWindowField,+ updateReasoningEffort: source.updateReasoningEffort,+ connectionTargets: source.connectionTargets,+ connectionTarget: source.connectionTarget,+ addConnection: source.addConnection,+ updateConnectionField: source.updateConnectionField,+ removeConnection: source.removeConnection,+ unlinkProfile: source.unlinkProfile,+ linkConnectionToServices: source.linkConnectionToServices,+ llmContextDetection: source.llmContextDetection,+ applyDetectedContextWindow: source.applyDetectedContextWindow,+ embeddingCapabilities: source.embeddingCapabilities,+ embeddingDefaultDim: source.embeddingDefaultDim,+ }), [+ source.catalog,+ source.draft,+ source.providers,+ source.catalogEditable,+ source.mutateCatalog,+ source.addProfile,+ source.removeActiveProfile,+ source.addModel,+ source.removeActiveModel,+ source.updateProfileField,+ source.updateModelField,+ source.updateModelBoolField,+ source.updateContextWindowField,+ source.updateReasoningEffort,+ source.connectionTargets,+ source.connectionTarget,+ source.addConnection,+ source.updateConnectionField,+ source.removeConnection,+ source.unlinkProfile,+ source.linkConnectionToServices,+ source.llmContextDetection,+ source.applyDetectedContextWindow,+ source.embeddingCapabilities,+ source.embeddingDefaultDim,+ ]);+ return <ModelCatalogContext.Provider value={value}>{children}</ModelCatalogContext.Provider>;+}++export function useModelCatalog(): ModelCatalogSlice {+ const value = useContext(ModelCatalogContext);+ if (!value) throw new Error("useModelCatalog must be used inside ModelCatalogProvider");+ return value;+}diff --git a/web/features/settings/store/SettingsDraftProvider.tsx b/web/features/settings/store/SettingsDraftProvider.tsxnew file mode 100644index 000000000..1a72fd8b1--- /dev/null+++ b/web/features/settings/store/SettingsDraftProvider.tsx@@ -0,0 +1,57 @@+"use client";++import { createContext, useContext, useMemo, type ReactNode } from "react";+import { useSettings, type SettingsContextValue } from "./SettingsStore";++type SettingsDraftSlice = Pick<+ SettingsContextValue,+ | "hasUnsavedChanges"+ | "saving"+ | "applying"+ | "saveDraft"+ | "applyCatalog"+ | "discardDraft"+ | "storedDraft"+ | "draftState"+ | "draftRevision"+ | "pendingExtensionPayload"+ | "registerExtension"+>;++const SettingsDraftContext = createContext<SettingsDraftSlice | null>(null);++export function SettingsDraftProvider({ children }: { children: ReactNode }) {+ const source = useSettings();+ const value = useMemo<SettingsDraftSlice>(() => ({+ hasUnsavedChanges: source.hasUnsavedChanges,+ saving: source.saving,+ applying: source.applying,+ saveDraft: source.saveDraft,+ applyCatalog: source.applyCatalog,+ discardDraft: source.discardDraft,+ storedDraft: source.storedDraft,+ draftState: source.draftState,+ draftRevision: source.draftRevision,+ pendingExtensionPayload: source.pendingExtensionPayload,+ registerExtension: source.registerExtension,+ }), [+ source.hasUnsavedChanges,+ source.saving,+ source.applying,+ source.saveDraft,+ source.applyCatalog,+ source.discardDraft,+ source.storedDraft,+ source.draftState,+ source.draftRevision,+ source.pendingExtensionPayload,+ source.registerExtension,+ ]);+ return <SettingsDraftContext.Provider value={value}>{children}</SettingsDraftContext.Provider>;+}++export function useSettingsDraft(): SettingsDraftSlice {+ const value = useContext(SettingsDraftContext);+ if (!value) throw new Error("useSettingsDraft must be used inside SettingsDraftProvider");+ return value;+}diff --git a/web/components/settings/SettingsContext.tsx b/web/features/settings/store/SettingsStore.tsxsimilarity index 99%rename from web/components/settings/SettingsContext.tsxrename to web/features/settings/store/SettingsStore.tsxindex ab9db5520..20c65fac9 100644--- a/web/components/settings/SettingsContext.tsx+++ b/web/features/settings/store/SettingsStore.tsx@@ -523,7 +523,7 @@ export interface SettingsExtension {payload?: unknown;}-type SettingsContextValue = {+export type SettingsContextValue = {// Statecatalog: Catalog;draft: Catalog;diff --git a/web/features/settings/store/UiSettingsProvider.tsx b/web/features/settings/store/UiSettingsProvider.tsxnew file mode 100644index 000000000..9f6610ec4--- /dev/null+++ b/web/features/settings/store/UiSettingsProvider.tsx@@ -0,0 +1,63 @@+"use client";++import { createContext, useContext, useMemo, type ReactNode } from "react";+import { useSettings, type SettingsContextValue } from "./SettingsStore";++type UiSettingsSlice = Pick<+ SettingsContextValue,+ | "theme"+ | "language"+ | "responseLanguage"+ | "codeBlockTheme"+ | "codeBlockShowLineNumbers"+ | "codeBlockWrapLongLines"+ | "updateTheme"+ | "updateLanguage"+ | "updateResponseLanguage"+ | "updateCodeBlockTheme"+ | "updateCodeBlockShowLineNumbers"+ | "updateCodeBlockWrapLongLines"+>;++const UiSettingsContext = createContext<UiSettingsSlice | null>(null);++export function UiSettingsProvider({ children }: { children: ReactNode }) {+ const source = useSettings();+ const value = useMemo<UiSettingsSlice>(+ () => ({+ theme: source.theme,+ language: source.language,+ responseLanguage: source.responseLanguage,+ codeBlockTheme: source.codeBlockTheme,+ codeBlockShowLineNumbers: source.codeBlockShowLineNumbers,+ codeBlockWrapLongLines: source.codeBlockWrapLongLines,+ updateTheme: source.updateTheme,+ updateLanguage: source.updateLanguage,+ updateResponseLanguage: source.updateResponseLanguage,+ updateCodeBlockTheme: source.updateCodeBlockTheme,+ updateCodeBlockShowLineNumbers: source.updateCodeBlockShowLineNumbers,+ updateCodeBlockWrapLongLines: source.updateCodeBlockWrapLongLines,+ }),+ [+ source.theme,+ source.language,+ source.responseLanguage,+ source.codeBlockTheme,+ source.codeBlockShowLineNumbers,+ source.codeBlockWrapLongLines,+ source.updateTheme,+ source.updateLanguage,+ source.updateResponseLanguage,+ source.updateCodeBlockTheme,+ source.updateCodeBlockShowLineNumbers,+ source.updateCodeBlockWrapLongLines,+ ],+ );+ return <UiSettingsContext.Provider value={value}>{children}</UiSettingsContext.Provider>;+}++export function useUiSettings(): UiSettingsSlice {+ const value = useContext(UiSettingsContext);+ if (!value) throw new Error("useUiSettings must be used inside UiSettingsProvider");+ return value;+}diff --git a/web/features/settings/store/index.ts b/web/features/settings/store/index.tsnew file mode 100644index 000000000..9b1eb5c82--- /dev/null+++ b/web/features/settings/store/index.ts@@ -0,0 +1,5 @@+export { SettingsProvider, useSettings } from "./SettingsStore";+export * from "./SettingsStore";+export { ModelCatalogProvider, useModelCatalog } from "./ModelCatalogProvider";+export { SettingsDraftProvider, useSettingsDraft } from "./SettingsDraftProvider";+export { UiSettingsProvider, useUiSettings } from "./UiSettingsProvider";diff --git a/web/lib/settings-nav.ts b/web/lib/settings-nav.tsindex 874b5a5b5..7ad4f83d8 100644--- a/web/lib/settings-nav.ts+++ b/web/lib/settings-nav.ts@@ -39,7 +39,7 @@ import {OpenClawGlyph,OpencodeGlyph,} from "@/components/agents/agent-icons";-import type { ServiceName } from "@/components/settings/SettingsContext";+import type { ServiceName } from "@/features/settings/store/SettingsStore";/*** Settings information architecture.diff --git a/web/tests/appearance-settings-page.test.ts b/web/tests/appearance-settings-page.test.tsindex efcfe4dd5..7f27f77c1 100644--- a/web/tests/appearance-settings-page.test.ts+++ b/web/tests/appearance-settings-page.test.ts@@ -7,11 +7,10 @@ import { CODE_BLOCK_THEME_OPTIONS } from "../components/common/code-block-themesconst appearancePagePath = path.join(process.cwd(),- "app",- "(utility)",+ "features","settings",- "appearance",- "page.tsx",+ "sections",+ "AppearanceSettingsSection.tsx",);function readAppearancePage() {diff --git a/web/tests/no-page-module-imports.test.ts b/web/tests/no-page-module-imports.test.tsnew file mode 100644index 000000000..81988d179--- /dev/null+++ b/web/tests/no-page-module-imports.test.ts@@ -0,0 +1,41 @@+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import test from "node:test";++const roots = ["app", "components", "features", "hooks", "lib", "shared"];++function sourceFiles(root: string): string[] {+ const absolute = path.resolve(process.cwd(), root);+ if (!fs.existsSync(absolute)) return [];+ const files: string[] = [];+ const visit = (directory: string) => {+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {+ const target = path.join(directory, entry.name);+ if (entry.isDirectory()) visit(target);+ else if (/\.(?:ts|tsx)$/.test(entry.name)) files.push(target);+ }+ };+ visit(absolute);+ return files;+}++test("frontend modules never import a Next route page", () => {+ const violations: string[] = [];+ for (const file of roots.flatMap(sourceFiles)) {+ const source = fs.readFileSync(file, "utf8");+ if (/from\s+["'][^"']*\/page["']/.test(source)) {+ violations.push(path.relative(process.cwd(), file));+ }+ }+ assert.deepEqual(violations, []);+});++test("the retired Settings Context path cannot return", () => {+ assert.equal(fs.existsSync(path.resolve(process.cwd(), "components/settings/SettingsContext.tsx")), false);+ const violations = roots+ .flatMap(sourceFiles)+ .filter((file) => fs.readFileSync(file, "utf8").includes("components/settings/SettingsContext"))+ .map((file) => path.relative(process.cwd(), file));+ assert.deepEqual(violations, []);+});diff --git a/web/tests/search-providers.test.ts b/web/tests/search-providers.test.tsindex a09fb8e61..55eb7163d 100644--- a/web/tests/search-providers.test.ts+++ b/web/tests/search-providers.test.ts@@ -2,7 +2,7 @@ import test from "node:test";import assert from "node:assert/strict";import { searchProviderFields } from "../components/settings/search-providers";-import type { ProviderOption } from "../components/settings/SettingsContext";+import type { ProviderOption } from "../features/settings/store/SettingsStore";// Options as `/api/v1/settings/provider-choices` serves them, derived from the// backend SEARCH_PROVIDERS spec table. The web app owns no provider table of itsdiff --git a/web/tests/settings-context-boolean-hydration.test.ts b/web/tests/settings-context-boolean-hydration.test.tsindex d2503d23a..3c6df52d6 100644--- a/web/tests/settings-context-boolean-hydration.test.ts+++ b/web/tests/settings-context-boolean-hydration.test.ts@@ -12,9 +12,10 @@ import {const settingsContextPath = path.join(process.cwd(),- "components",+ "features","settings",- "SettingsContext.tsx",+ "store",+ "SettingsStore.tsx",);function readSettingsContextSource() {diff --git a/web/tests/settings-context-ui-sync.test.ts b/web/tests/settings-context-ui-sync.test.tsindex 11082763f..14142cc38 100644--- a/web/tests/settings-context-ui-sync.test.ts+++ b/web/tests/settings-context-ui-sync.test.ts@@ -38,7 +38,7 @@ function mockWindow() {mockWindow();-import * as settingsContext from "../components/settings/SettingsContext";+import * as settingsContext from "../features/settings/store/SettingsStore";import {CODE_BLOCK_SETTINGS_EVENT,readStoredCodeBlockShowLineNumbers,@@ -48,9 +48,10 @@ import {const settingsContextPath = path.join(process.cwd(),- "components",+ "features","settings",- "SettingsContext.tsx",+ "store",+ "SettingsStore.tsx",);function readSettingsContextSource() {diff --git a/web/tests/settings-provider-slices.test.ts b/web/tests/settings-provider-slices.test.tsnew file mode 100644index 000000000..e3ef0d59b--- /dev/null+++ b/web/tests/settings-provider-slices.test.ts@@ -0,0 +1,34 @@+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import test from "node:test";++const read = (relative: string) => fs.readFileSync(path.resolve(process.cwd(), relative), "utf8");++test("settings layout installs independently memoized provider slices", () => {+ const layout = read("app/(utility)/settings/layout.tsx");+ for (const provider of ["UiSettingsProvider", "ModelCatalogProvider", "SettingsDraftProvider"]) {+ assert.match(layout, new RegExp(`<${provider}>`));+ }++ const ui = read("features/settings/store/UiSettingsProvider.tsx");+ const catalog = read("features/settings/store/ModelCatalogProvider.tsx");+ const draft = read("features/settings/store/SettingsDraftProvider.tsx");+ for (const source of [ui, catalog, draft]) {+ assert.match(source, /useMemo/);+ assert.doesNotMatch(source, /\}, \[source\]\)/);+ }+});++test("appearance consumes only the UI preference slice", () => {+ const appearance = read("features/settings/sections/AppearanceSettingsSection.tsx");+ assert.match(appearance, /useUiSettings\(\)/);+ assert.doesNotMatch(appearance, /useSettings\(\)/);+});++test("continuous settings imports feature sections, never route modules", () => {+ const page = read("app/(utility)/settings/page.tsx");+ assert.match(page, /features\/settings\/sections\/ModelsSettingsSection/);+ assert.match(page, /features\/settings\/sections\/ChatSettingsSection/);+ assert.doesNotMatch(page, /from "\.\/.+\/page"|from "\.\/.+page"/);+});diff --git a/web/tests/subagent-harnesses.test.ts b/web/tests/subagent-harnesses.test.tsindex 8ad06ab4b..0c6df8d33 100644--- a/web/tests/subagent-harnesses.test.ts+++ b/web/tests/subagent-harnesses.test.ts@@ -55,7 +55,7 @@ test('Gemini CLI is retired and agent glyphs use official local assets', () => {test('new harnesses have settings routes and category sections', () => {const editor = readWebFile('components', 'settings', 'SubagentSettingsEditor.tsx')- const category = readWebFile('app', '(utility)', 'settings', 'agents', 'page.tsx')+ const category = readWebFile('features', 'settings', 'sections', 'AgentsSettingsSection.tsx')const nav = readWebFile('lib', 'settings-nav.ts')for (const harness of HARNESSES) {diff --git a/web/tests/wire-api-settings-contract.test.ts b/web/tests/wire-api-settings-contract.test.tsindex 3799c665b..c2441fa2d 100644--- a/web/tests/wire-api-settings-contract.test.ts+++ b/web/tests/wire-api-settings-contract.test.ts@@ -9,7 +9,7 @@ const EDITOR = path.resolve();const CONTEXT = path.resolve(process.cwd(),- "components/settings/SettingsContext.tsx",+ "features/settings/store/SettingsStore.tsx",);const MAIN = path.resolve(process.cwd(),