mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 20:11:38 +08:00
fix(settings): make Save draft real, and stop losing edits on navigation
Save Draft and Apply were the same write. Both persisted to the live files
and both invalidated the runtime caches, so nothing but their labels told
them apart — and Save Draft only ever wrote the model catalog, while half
the settings pages (memory, starting points, network, attachments,
document parsing) keep their state outside it.
The result was silent data loss, reproducible in four steps: open Starting
points, change 20 to 44, press Save Draft, read "Draft saved" — the server
still had 20, and navigating away lost the edit with no warning. The
button was enabled, because `hasUnsavedChanges` counted extension state
that `saveCatalog` never touched.
So a draft is now a place rather than a label. One envelope holding the
catalog and a payload per page, stored beside the live settings and read
by nothing else:
Save draft → envelope written, runtime untouched
Apply → live files written, envelope cleared
Discard → envelope dropped, back to what is live
Two other losses closed along the way. Unsaved page state now lives on the
provider instead of the page, so moving around inside Settings keeps it —
a settings page unmounts on every navigation, which is why the edit
vanished. And an edit that exists nowhere else warns before the tab is
closed or reloaded.
The toolbar had no way to say "there is a draft waiting", so a draft saved
yesterday would have sat there unexplained; it now reports which of the
three states you are in. The storage path moved into that line's tooltip —
self-hosted users occasionally want to know which file backs a page, but
it is a developer fact and was on screen for everyone.
This commit is contained in:
@@ -42,6 +42,12 @@ from deeptutor.services.config.runtime_settings import (
|
||||
CHAT_ATTACHMENT_MAX_TOTAL_MB_RANGE,
|
||||
compute_ws_max_size,
|
||||
)
|
||||
from deeptutor.services.config.settings_draft import (
|
||||
get_settings_draft_service,
|
||||
is_empty_draft,
|
||||
merge_draft_secrets,
|
||||
redact_draft,
|
||||
)
|
||||
from deeptutor.services.embedding.client import reset_embedding_client
|
||||
from deeptutor.services.llm.client import reset_llm_client
|
||||
from deeptutor.services.llm.config import clear_llm_config_cache
|
||||
@@ -185,6 +191,14 @@ class CatalogPayload(BaseModel):
|
||||
catalog: dict[str, Any]
|
||||
|
||||
|
||||
class SettingsDraftPayload(BaseModel):
|
||||
"""The unapplied settings envelope, as the settings UI holds it."""
|
||||
|
||||
catalog: dict[str, Any] | None = None
|
||||
# Opaque per-page state, keyed by the string the page registers with.
|
||||
extensions: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class CodexReasoningEffortUpdate(BaseModel):
|
||||
model: str = Field(min_length=1)
|
||||
reasoning_effort: str | None = None
|
||||
@@ -1375,20 +1389,70 @@ async def update_catalog(payload: CatalogPayload):
|
||||
return {"catalog": redact_catalog_secrets(catalog)}
|
||||
|
||||
|
||||
@router.get("/draft")
|
||||
async def get_settings_draft():
|
||||
"""Return the unapplied draft, or nothing when there is none.
|
||||
|
||||
The draft is deliberately invisible to every other read path: nothing that
|
||||
resolves runtime configuration looks here, which is the whole difference
|
||||
between saving a draft and applying it.
|
||||
"""
|
||||
_require_settings_admin()
|
||||
draft = get_settings_draft_service().load()
|
||||
if is_empty_draft(draft):
|
||||
return {"draft": None}
|
||||
return {"draft": redact_draft(draft)}
|
||||
|
||||
|
||||
@router.put("/draft")
|
||||
async def update_settings_draft(payload: SettingsDraftPayload):
|
||||
_require_settings_admin()
|
||||
service = get_settings_draft_service()
|
||||
stored = service.load()
|
||||
merged = merge_draft_secrets(
|
||||
payload.model_dump(),
|
||||
stored,
|
||||
get_model_catalog_service().load(),
|
||||
)
|
||||
if is_empty_draft(merged):
|
||||
service.clear()
|
||||
return {"draft": None}
|
||||
saved = service.save(merged)
|
||||
return {"draft": redact_draft(saved)}
|
||||
|
||||
|
||||
@router.delete("/draft")
|
||||
async def discard_settings_draft():
|
||||
_require_settings_admin()
|
||||
get_settings_draft_service().clear()
|
||||
return {"draft": None}
|
||||
|
||||
|
||||
@router.post("/apply")
|
||||
async def apply_catalog(payload: CatalogPayload | None = None):
|
||||
"""Move settings into the files the runtime reads, and clear the draft.
|
||||
|
||||
With no body this promotes the stored draft's catalog, which is how the
|
||||
settings UI applies: credentials that only ever existed in a draft would
|
||||
otherwise have to round-trip through the browser as placeholders and come
|
||||
back resolving to the previous key.
|
||||
"""
|
||||
_require_settings_admin()
|
||||
service = get_model_catalog_service()
|
||||
draft_service = get_settings_draft_service()
|
||||
current = service.load()
|
||||
catalog = (
|
||||
reconcile_codex_catalog_update(
|
||||
current,
|
||||
restore_catalog_secrets(payload.catalog, current),
|
||||
if payload is not None:
|
||||
proposed = restore_catalog_secrets(payload.catalog, current)
|
||||
else:
|
||||
draft_catalog = draft_service.load().get("catalog")
|
||||
proposed = (
|
||||
restore_catalog_secrets(draft_catalog, current)
|
||||
if isinstance(draft_catalog, dict)
|
||||
else current
|
||||
)
|
||||
if payload is not None
|
||||
else current
|
||||
)
|
||||
catalog = reconcile_codex_catalog_update(current, proposed)
|
||||
applied = service.apply(catalog)
|
||||
draft_service.clear()
|
||||
_invalidate_runtime_caches()
|
||||
return {
|
||||
"message": "Catalog applied to runtime settings.",
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Unapplied settings, held off the runtime path.
|
||||
|
||||
Settings offers two promises — "Save Draft" and "Apply" — and until now they
|
||||
were the same write: both persisted to the live files and both invalidated the
|
||||
runtime caches, so the only thing distinguishing them was their labels. Worse,
|
||||
"Save Draft" only ever wrote the model catalog, while half the settings pages
|
||||
(memory, starting points, network, attachments, document parsing) keep their
|
||||
state outside it. Editing one of those, pressing Save Draft and reading
|
||||
"Draft saved" persisted nothing at all, and navigating away lost the edit.
|
||||
|
||||
So a draft is now a real place: one envelope, stored beside the live settings
|
||||
but read by nothing except this module. Apply is what moves it into the files
|
||||
the runtime resolves against, and clears it.
|
||||
|
||||
Save Draft → envelope written, runtime untouched
|
||||
Apply → live files written, envelope cleared
|
||||
|
||||
The envelope holds the whole catalog and an opaque payload per settings page
|
||||
that owns state outside it, keyed by the same string the page registers with.
|
||||
Payloads are opaque on purpose: the pages that produce them are the only code
|
||||
that understands them, and inventing a server-side schema for each one would
|
||||
buy validation at the cost of a second definition to keep in sync.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
from deeptutor.services.path_service import get_path_service
|
||||
|
||||
from .model_catalog import redact_catalog_secrets, restore_catalog_secrets
|
||||
|
||||
DRAFT_VERSION = 1
|
||||
|
||||
|
||||
def _empty_draft() -> dict[str, Any]:
|
||||
return {"version": DRAFT_VERSION, "updated_at": "", "catalog": None, "extensions": {}}
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
class SettingsDraftService:
|
||||
"""Read/write the unapplied settings envelope."""
|
||||
|
||||
_instances: dict[str, "SettingsDraftService"] = {}
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self._lock = threading.RLock()
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls, path: Path | None = None) -> "SettingsDraftService":
|
||||
resolved = (path or get_path_service().get_settings_file("settings_draft")).resolve()
|
||||
key = str(resolved)
|
||||
if key not in cls._instances:
|
||||
cls._instances[key] = cls(resolved)
|
||||
return cls._instances[key]
|
||||
|
||||
def load(self) -> dict[str, Any]:
|
||||
if not self.path.exists() or self.path.stat().st_size == 0:
|
||||
return _empty_draft()
|
||||
try:
|
||||
loaded = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
# A corrupt draft is not worth failing a settings page over; the
|
||||
# live configuration is unaffected either way.
|
||||
return _empty_draft()
|
||||
if not isinstance(loaded, dict):
|
||||
return _empty_draft()
|
||||
draft = _empty_draft()
|
||||
draft.update({key: loaded.get(key, draft[key]) for key in draft})
|
||||
if not isinstance(draft.get("extensions"), dict):
|
||||
draft["extensions"] = {}
|
||||
return draft
|
||||
|
||||
def save(self, draft: dict[str, Any]) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
normalized = _empty_draft()
|
||||
normalized.update({key: draft.get(key, normalized[key]) for key in normalized})
|
||||
if not isinstance(normalized.get("extensions"), dict):
|
||||
normalized["extensions"] = {}
|
||||
normalized["version"] = DRAFT_VERSION
|
||||
normalized["updated_at"] = _now()
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temp_name = tempfile.mkstemp(
|
||||
prefix=f".{self.path.name}.", suffix=".tmp", dir=self.path.parent
|
||||
)
|
||||
temp_path = Path(temp_name)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
|
||||
json.dump(normalized, handle, indent=2, ensure_ascii=False)
|
||||
handle.write("\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, self.path)
|
||||
finally:
|
||||
temp_path.unlink(missing_ok=True)
|
||||
return normalized
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self.path.unlink(missing_ok=True)
|
||||
|
||||
def has_content(self, draft: dict[str, Any] | None = None) -> bool:
|
||||
loaded = draft if draft is not None else self.load()
|
||||
return bool(loaded.get("catalog")) or bool(loaded.get("extensions"))
|
||||
|
||||
|
||||
def is_empty_draft(draft: dict[str, Any] | None) -> bool:
|
||||
if not draft:
|
||||
return True
|
||||
return not draft.get("catalog") and not draft.get("extensions")
|
||||
|
||||
|
||||
def redact_draft(draft: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return an API-safe envelope.
|
||||
|
||||
Only the catalog half can be redacted meaningfully — extension payloads are
|
||||
opaque here. None of the settings pages backed by them hold credentials
|
||||
(they carry counts, budgets, ports and toggles), so there is nothing to
|
||||
mask; a page that ever does needs its own handling rather than a guess at
|
||||
this layer.
|
||||
"""
|
||||
safe = deepcopy(draft)
|
||||
catalog = safe.get("catalog")
|
||||
if isinstance(catalog, dict):
|
||||
safe["catalog"] = redact_catalog_secrets(catalog)
|
||||
return safe
|
||||
|
||||
|
||||
def merge_draft_secrets(
|
||||
proposed: dict[str, Any],
|
||||
stored: dict[str, Any],
|
||||
live_catalog: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Resolve masked credentials in an incoming draft.
|
||||
|
||||
A key typed into a draft and never applied lives only in the draft file, so
|
||||
the placeholder that comes back has to resolve against the draft first and
|
||||
the live catalog second. Getting that order wrong would quietly replace a
|
||||
newly typed key with the old one every time the draft was re-saved.
|
||||
"""
|
||||
merged = deepcopy(proposed)
|
||||
catalog = merged.get("catalog")
|
||||
if not isinstance(catalog, dict):
|
||||
return merged
|
||||
stored_catalog = stored.get("catalog")
|
||||
if isinstance(stored_catalog, dict):
|
||||
catalog = restore_catalog_secrets(catalog, stored_catalog)
|
||||
merged["catalog"] = restore_catalog_secrets(catalog, live_catalog)
|
||||
return merged
|
||||
|
||||
|
||||
def get_settings_draft_service() -> SettingsDraftService:
|
||||
"""Resolve the draft for the acting scope, mirroring the model catalog.
|
||||
|
||||
A non-admin never edits these settings, so their draft — if the UI somehow
|
||||
offered one — belongs to the admin scope they are reading, not to a private
|
||||
file that nothing would ever apply.
|
||||
"""
|
||||
try:
|
||||
from deeptutor.multi_user.context import get_current_user
|
||||
from deeptutor.multi_user.paths import get_admin_path_service
|
||||
|
||||
if not get_current_user().is_admin:
|
||||
return SettingsDraftService.get_instance(
|
||||
get_admin_path_service().get_settings_file("settings_draft")
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return SettingsDraftService.get_instance(get_path_service().get_settings_file("settings_draft"))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"SettingsDraftService",
|
||||
"get_settings_draft_service",
|
||||
"is_empty_draft",
|
||||
"merge_draft_secrets",
|
||||
"redact_draft",
|
||||
]
|
||||
@@ -0,0 +1,110 @@
|
||||
"""A draft is somewhere the runtime does not look."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from deeptutor.services.config.model_catalog import CATALOG_SECRET_MASK
|
||||
from deeptutor.services.config.settings_draft import (
|
||||
SettingsDraftService,
|
||||
is_empty_draft,
|
||||
merge_draft_secrets,
|
||||
redact_draft,
|
||||
)
|
||||
|
||||
|
||||
def _service(tmp_path: Path) -> SettingsDraftService:
|
||||
return SettingsDraftService(path=tmp_path / "settings_draft.json")
|
||||
|
||||
|
||||
def _catalog(api_key: str) -> dict[str, Any]:
|
||||
return {
|
||||
"version": 1,
|
||||
"connections": [],
|
||||
"services": {
|
||||
"llm": {
|
||||
"active_profile_id": "p1",
|
||||
"active_model_id": "m1",
|
||||
"profiles": [
|
||||
{
|
||||
"id": "p1",
|
||||
"name": "OpenAI",
|
||||
"api_key": api_key,
|
||||
"models": [{"id": "m1", "model": "gpt-5"}],
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_missing_file_reads_as_an_empty_draft(tmp_path: Path) -> None:
|
||||
assert is_empty_draft(_service(tmp_path).load())
|
||||
|
||||
|
||||
def test_a_corrupt_draft_does_not_take_the_page_down(tmp_path: Path) -> None:
|
||||
service = _service(tmp_path)
|
||||
service.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
service.path.write_text("{ not json", encoding="utf-8")
|
||||
|
||||
assert is_empty_draft(service.load())
|
||||
|
||||
|
||||
def test_saving_records_both_halves_and_a_timestamp(tmp_path: Path) -> None:
|
||||
service = _service(tmp_path)
|
||||
|
||||
saved = service.save(
|
||||
{"catalog": _catalog("sk-live"), "extensions": {"chat-starters": {"trace_count": 44}}}
|
||||
)
|
||||
|
||||
assert saved["extensions"]["chat-starters"] == {"trace_count": 44}
|
||||
assert saved["updated_at"]
|
||||
reloaded = service.load()
|
||||
assert reloaded["extensions"] == saved["extensions"]
|
||||
|
||||
|
||||
def test_redaction_masks_the_catalog_half(tmp_path: Path) -> None:
|
||||
service = _service(tmp_path)
|
||||
saved = service.save({"catalog": _catalog("sk-live"), "extensions": {}})
|
||||
|
||||
redacted = redact_draft(saved)
|
||||
|
||||
profile = redacted["catalog"]["services"]["llm"]["profiles"][0]
|
||||
assert profile["api_key"] == CATALOG_SECRET_MASK
|
||||
# The stored copy is untouched — redaction is for the wire only.
|
||||
assert service.load()["catalog"]["services"]["llm"]["profiles"][0]["api_key"] == "sk-live"
|
||||
|
||||
|
||||
def test_a_key_typed_only_into_a_draft_survives_re_saving_it(tmp_path: Path) -> None:
|
||||
"""The placeholder has to resolve against the draft, not just the live file."""
|
||||
service = _service(tmp_path)
|
||||
stored = service.save({"catalog": _catalog("sk-drafted"), "extensions": {}})
|
||||
# What the browser sends back after a round trip: everything masked.
|
||||
proposed = redact_draft(stored)
|
||||
proposed["catalog"]["services"]["llm"]["profiles"][0]["name"] = "Renamed"
|
||||
|
||||
merged = merge_draft_secrets(proposed, stored, _catalog("sk-live"))
|
||||
|
||||
profile = merged["catalog"]["services"]["llm"]["profiles"][0]
|
||||
assert profile["api_key"] == "sk-drafted"
|
||||
assert profile["name"] == "Renamed"
|
||||
|
||||
|
||||
def test_an_untouched_key_still_falls_back_to_the_live_catalog(tmp_path: Path) -> None:
|
||||
service = _service(tmp_path)
|
||||
proposed = redact_draft({"catalog": _catalog(CATALOG_SECRET_MASK), "extensions": {}})
|
||||
|
||||
merged = merge_draft_secrets(proposed, service.load(), _catalog("sk-live"))
|
||||
|
||||
assert merged["catalog"]["services"]["llm"]["profiles"][0]["api_key"] == "sk-live"
|
||||
|
||||
|
||||
def test_clearing_removes_the_file(tmp_path: Path) -> None:
|
||||
service = _service(tmp_path)
|
||||
service.save({"catalog": _catalog("sk-live"), "extensions": {}})
|
||||
|
||||
service.clear()
|
||||
|
||||
assert not service.path.exists()
|
||||
assert is_empty_draft(service.load())
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} 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;
|
||||
@@ -45,7 +46,8 @@ function normalizeDraft(
|
||||
|
||||
export default function AttachmentSettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { registerExtension } = useSettings();
|
||||
const { registerExtension, pendingExtensionPayload, draftRevision } =
|
||||
useSettings();
|
||||
const [payload, setPayload] = useState<AttachmentSettingsPayload | null>(
|
||||
null,
|
||||
);
|
||||
@@ -60,7 +62,7 @@ export default function AttachmentSettingsPage() {
|
||||
setError(null);
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
apiUrl("/api/v1/settings/chat-attachments"),
|
||||
apiUrl(EXTENSION_ENDPOINTS["chat-attachments"]),
|
||||
);
|
||||
const data = (await response.json().catch(() => ({}))) as
|
||||
| AttachmentSettingsPayload
|
||||
@@ -75,7 +77,10 @@ export default function AttachmentSettingsPage() {
|
||||
if (cancelled) return;
|
||||
const next = data as AttachmentSettingsPayload;
|
||||
setPayload(next);
|
||||
setDraft(normalizeDraft(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));
|
||||
@@ -88,7 +93,7 @@ export default function AttachmentSettingsPage() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [t]);
|
||||
}, [draftRevision, pendingExtensionPayload, t]);
|
||||
|
||||
const dirty = useMemo(() => {
|
||||
if (!payload || !draft) return false;
|
||||
@@ -110,7 +115,7 @@ export default function AttachmentSettingsPage() {
|
||||
setError(null);
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
apiUrl("/api/v1/settings/chat-attachments"),
|
||||
apiUrl(EXTENSION_ENDPOINTS["chat-attachments"]),
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -136,9 +141,9 @@ export default function AttachmentSettingsPage() {
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
registerExtension("chat-attachments", { dirty, save });
|
||||
registerExtension("chat-attachments", { dirty, save, payload: draft });
|
||||
return () => registerExtension("chat-attachments", null);
|
||||
}, [dirty, save, registerExtension]);
|
||||
}, [dirty, draft, save, registerExtension]);
|
||||
|
||||
const setField = (field: keyof AttachmentSettings) => (value: number) =>
|
||||
setDraft((current) => (current ? { ...current, [field]: value } : current));
|
||||
|
||||
@@ -5,6 +5,7 @@ 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,
|
||||
@@ -84,7 +85,8 @@ function isValidCapabilitiesDTO(
|
||||
|
||||
export default function CapabilitiesSettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { registerExtension } = useSettings();
|
||||
const { registerExtension, pendingExtensionPayload, draftRevision } =
|
||||
useSettings();
|
||||
const [settings, setSettings] = useState<CapabilitiesSettingsDTO | null>(
|
||||
null,
|
||||
);
|
||||
@@ -94,7 +96,7 @@ export default function CapabilitiesSettingsPage() {
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const res = await apiFetch(apiUrl("/api/v1/capabilities/settings"));
|
||||
const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.capabilities));
|
||||
if (!res.ok) {
|
||||
setLoadError(
|
||||
t(
|
||||
@@ -113,7 +115,10 @@ export default function CapabilitiesSettingsPage() {
|
||||
);
|
||||
return;
|
||||
}
|
||||
setSettings(data);
|
||||
const pending = pendingExtensionPayload("capabilities") as
|
||||
| CapabilitiesSettingsDTO
|
||||
| undefined;
|
||||
setSettings(pending ?? data);
|
||||
setServerSnapshot(data);
|
||||
setLoadError(null);
|
||||
} catch (err) {
|
||||
@@ -123,14 +128,15 @@ export default function CapabilitiesSettingsPage() {
|
||||
: t("Failed to load capability settings."),
|
||||
);
|
||||
}
|
||||
}, [t]);
|
||||
}, [pendingExtensionPayload, t]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
void load();
|
||||
}, 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [load]);
|
||||
// Re-read when a draft is discarded so the page drops its stale copy.
|
||||
}, [draftRevision, load]);
|
||||
|
||||
const dirty =
|
||||
!!settings &&
|
||||
@@ -144,7 +150,7 @@ export default function CapabilitiesSettingsPage() {
|
||||
const save = useCallback(async () => {
|
||||
const current = settingsRef.current;
|
||||
if (!current) return;
|
||||
const res = await apiFetch(apiUrl("/api/v1/capabilities/settings"), {
|
||||
const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.capabilities), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(current),
|
||||
@@ -165,9 +171,9 @@ export default function CapabilitiesSettingsPage() {
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
registerExtension("capabilities", { dirty, save });
|
||||
registerExtension("capabilities", { dirty, save, payload: settings });
|
||||
return () => registerExtension("capabilities", null);
|
||||
}, [dirty, save, registerExtension]);
|
||||
}, [dirty, save, settings, registerExtension]);
|
||||
|
||||
function patchChat<K extends keyof ChatBlock>(key: K, value: ChatBlock[K]) {
|
||||
if (!settings) return;
|
||||
|
||||
@@ -5,6 +5,7 @@ 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,
|
||||
@@ -35,24 +36,30 @@ interface MemorySettingsDTO {
|
||||
|
||||
export default function MemorySettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { registerExtension } = useSettings();
|
||||
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("/api/v1/memory/settings"))
|
||||
void apiFetch(apiUrl(EXTENSION_ENDPOINTS.memory))
|
||||
.then((res) => res.json() as Promise<MemorySettingsDTO>)
|
||||
.then((data) => {
|
||||
if (cancelled) return;
|
||||
setSettings(data);
|
||||
// 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 &&
|
||||
@@ -68,7 +75,7 @@ export default function MemorySettingsPage() {
|
||||
const save = useCallback(async () => {
|
||||
const current = settingsRef.current;
|
||||
if (!current) return;
|
||||
const res = await apiFetch(apiUrl("/api/v1/memory/settings"), {
|
||||
const res = await apiFetch(apiUrl(EXTENSION_ENDPOINTS.memory), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(current),
|
||||
@@ -79,9 +86,9 @@ export default function MemorySettingsPage() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
registerExtension("memory", { dirty, save });
|
||||
registerExtension("memory", { dirty, save, payload: settings });
|
||||
return () => registerExtension("memory", null);
|
||||
}, [dirty, save, registerExtension]);
|
||||
}, [dirty, save, settings, registerExtension]);
|
||||
|
||||
function patch<K extends keyof MemorySettingsDTO>(
|
||||
key: K,
|
||||
|
||||
@@ -102,7 +102,8 @@ function DetailTile({
|
||||
*/
|
||||
function ChatResponseTimeoutSection() {
|
||||
const { t } = useTranslation();
|
||||
const { registerExtension } = useSettings();
|
||||
const { registerExtension, pendingExtensionPayload, draftRevision } =
|
||||
useSettings();
|
||||
const [seconds, setSeconds] = useState<number>(
|
||||
DEFAULT_CHAT_RESPONSE_TIMEOUT_SECONDS,
|
||||
);
|
||||
@@ -163,9 +164,13 @@ function ChatResponseTimeoutSection() {
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
registerExtension("chat-timeout", { dirty, save });
|
||||
registerExtension("chat-timeout", {
|
||||
dirty,
|
||||
save,
|
||||
payload: { chat_response_timeout: seconds },
|
||||
});
|
||||
return () => registerExtension("chat-timeout", null);
|
||||
}, [dirty, save, registerExtension]);
|
||||
}, [dirty, save, seconds, registerExtension]);
|
||||
|
||||
return (
|
||||
<SettingSection
|
||||
@@ -205,7 +210,8 @@ function ChatResponseTimeoutSection() {
|
||||
|
||||
export default function NetworkSettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { registerExtension } = useSettings();
|
||||
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);
|
||||
@@ -234,8 +240,12 @@ export default function NetworkSettingsPage() {
|
||||
if (cancelled) return;
|
||||
const next = data as NetworkSettingsPayload;
|
||||
setPayload(next);
|
||||
setDraft(normalizeDraft(next));
|
||||
setCorsText((next.settings.cors_origins || []).join("\n"));
|
||||
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));
|
||||
@@ -248,7 +258,7 @@ export default function NetworkSettingsPage() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [t]);
|
||||
}, [draftRevision, pendingExtensionPayload, t]);
|
||||
|
||||
const dirty = useMemo(() => {
|
||||
if (!payload || !draft) return false;
|
||||
@@ -301,9 +311,9 @@ export default function NetworkSettingsPage() {
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
registerExtension("network", { dirty, save });
|
||||
registerExtension("network", { dirty, save, payload: draft });
|
||||
return () => registerExtension("network", null);
|
||||
}, [dirty, save, registerExtension]);
|
||||
}, [dirty, draft, save, registerExtension]);
|
||||
|
||||
return (
|
||||
<div data-tour="tour-network">
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} 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 };
|
||||
|
||||
@@ -23,7 +24,8 @@ type StarterSettingsPayload = {
|
||||
|
||||
export default function StarterSettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { registerExtension } = useSettings();
|
||||
const { registerExtension, pendingExtensionPayload, draftRevision } =
|
||||
useSettings();
|
||||
const [payload, setPayload] = useState<StarterSettingsPayload | null>(null);
|
||||
const [draft, setDraft] = useState<StarterSettings | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -36,7 +38,7 @@ export default function StarterSettingsPage() {
|
||||
setError(null);
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
apiUrl("/api/v1/settings/chat-starters"),
|
||||
apiUrl(EXTENSION_ENDPOINTS["chat-starters"]),
|
||||
);
|
||||
const data = (await response.json().catch(() => ({}))) as
|
||||
| StarterSettingsPayload
|
||||
@@ -51,7 +53,13 @@ export default function StarterSettingsPage() {
|
||||
if (cancelled) return;
|
||||
const next = data as StarterSettingsPayload;
|
||||
setPayload(next);
|
||||
setDraft({ ...next.settings });
|
||||
// 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));
|
||||
@@ -63,7 +71,7 @@ export default function StarterSettingsPage() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [t]);
|
||||
}, [draftRevision, pendingExtensionPayload, t]);
|
||||
|
||||
const dirty = useMemo(
|
||||
() =>
|
||||
@@ -82,7 +90,7 @@ export default function StarterSettingsPage() {
|
||||
setError(null);
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
apiUrl("/api/v1/settings/chat-starters"),
|
||||
apiUrl(EXTENSION_ENDPOINTS["chat-starters"]),
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -108,9 +116,9 @@ export default function StarterSettingsPage() {
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
registerExtension("chat-starters", { dirty, save });
|
||||
registerExtension("chat-starters", { dirty, save, payload: draft });
|
||||
return () => registerExtension("chat-starters", null);
|
||||
}, [dirty, save, registerExtension]);
|
||||
}, [dirty, draft, save, registerExtension]);
|
||||
|
||||
const bounds = payload?.bounds.trace_count;
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import { useAppShell } from "@/context/AppShellContext";
|
||||
import { apiFetch, apiUrl } from "@/lib/api";
|
||||
import { invalidateLLMOptionsCache } from "@/lib/llm-options";
|
||||
import { setModelReasoningEffort } from "@/lib/reasoning-effort";
|
||||
import { applyExtensionPayload } from "@/lib/settings-extensions";
|
||||
import { setTheme as applyThemePreference } from "@/lib/theme";
|
||||
|
||||
// ─── Domain types ─────────────────────────────────────────────────────────
|
||||
@@ -268,6 +269,22 @@ export type ServiceReadiness =
|
||||
| "passed"
|
||||
| "failed";
|
||||
|
||||
/**
|
||||
* Where the current settings state lives.
|
||||
* clean — identical to what is applied
|
||||
* unsaved — edited, not written anywhere yet
|
||||
* saved — written to the draft store, not applied
|
||||
*/
|
||||
export type DraftState = "clean" | "unsaved" | "saved";
|
||||
|
||||
/** What the server holds as unapplied. `catalog` comes back redacted. */
|
||||
export type StoredDraft = {
|
||||
version: number;
|
||||
updated_at: string;
|
||||
catalog: Catalog | null;
|
||||
extensions: Record<string, unknown>;
|
||||
};
|
||||
|
||||
type SettingsPayload = {
|
||||
ui: UiSettings;
|
||||
catalog?: Catalog;
|
||||
@@ -503,6 +520,13 @@ function readStoredDiagnosticsResults(): Partial<
|
||||
export interface SettingsExtension {
|
||||
dirty: boolean;
|
||||
save: () => Promise<void>;
|
||||
/**
|
||||
* The page's current editable state. Retained by the provider after the
|
||||
* page unmounts, so navigating away from a half-edited settings page no
|
||||
* longer throws the edit away, and stored in the draft so it survives a
|
||||
* reload. Pages that omit it keep the old (lossy) behaviour.
|
||||
*/
|
||||
payload?: unknown;
|
||||
}
|
||||
|
||||
type SettingsContextValue = {
|
||||
@@ -589,8 +613,15 @@ type SettingsContextValue = {
|
||||
// Save / apply
|
||||
saving: boolean;
|
||||
applying: boolean;
|
||||
saveCatalog: () => Promise<void>;
|
||||
saveDraft: () => Promise<void>;
|
||||
applyCatalog: () => Promise<void>;
|
||||
discardDraft: () => Promise<void>;
|
||||
/** A draft parked on the server, waiting to be applied. */
|
||||
storedDraft: StoredDraft | null;
|
||||
draftState: DraftState;
|
||||
/** Bumped when a draft is discarded so pages re-read from the server. */
|
||||
draftRevision: number;
|
||||
pendingExtensionPayload: (key: string) => unknown;
|
||||
|
||||
// Sub-page extension hooks. Sub-routes (e.g. /settings/memory) that own
|
||||
// state outside the catalog register a "dirty + save" pair so the global
|
||||
@@ -665,6 +696,10 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
const [connectionTargets, setConnectionTargets] = useState<ConnectionTarget[]>(
|
||||
[],
|
||||
);
|
||||
const [storedDraft, setStoredDraft] = useState<StoredDraft | null>(null);
|
||||
// Signature of the envelope as last written to the draft store.
|
||||
const [savedSignature, setSavedSignature] = useState<string | null>(null);
|
||||
const [draftRevision, setDraftRevision] = useState(0);
|
||||
const [toast, setToast] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [applying, setApplying] = useState(false);
|
||||
@@ -685,34 +720,58 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
// Extensions register their latest dirty/save on each render. Keep the
|
||||
// derived dirty state explicit instead of using an indirect version counter.
|
||||
const extensionsRef = useRef<Map<string, SettingsExtension>>(new Map());
|
||||
const [hasDirtyExtension, setHasDirtyExtension] = useState(false);
|
||||
// Pending edits from settings pages that keep state outside the catalog,
|
||||
// kept here rather than in the pages themselves. A page unmounts on every
|
||||
// navigation inside Settings; holding its unsaved payload at the provider
|
||||
// is what makes leaving the page non-destructive.
|
||||
const pendingRef = useRef<Map<string, unknown>>(new Map());
|
||||
// A signature of the pending payloads rather than just their keys: the
|
||||
// toolbar has to notice the second edit to the same field, not only the
|
||||
// first, or "Draft saved" would keep showing after further typing.
|
||||
const [pendingSignature, setPendingSignature] = useState("{}");
|
||||
const syncPendingKeys = useCallback(() => {
|
||||
const entries = Array.from(pendingRef.current.entries()).sort(
|
||||
([a], [b]) => (a < b ? -1 : a > b ? 1 : 0),
|
||||
);
|
||||
const next = JSON.stringify(Object.fromEntries(entries));
|
||||
setPendingSignature((current) => (current === next ? current : next));
|
||||
}, []);
|
||||
|
||||
const registerExtension = useCallback(
|
||||
(key: string, ext: SettingsExtension | null) => {
|
||||
const map = extensionsRef.current;
|
||||
const prev = map.get(key);
|
||||
if (ext === null) {
|
||||
if (prev === undefined) return;
|
||||
// Deregistration means "this page left the screen", never "discard
|
||||
// what was typed" — the pending payload deliberately outlives it.
|
||||
map.delete(key);
|
||||
setHasDirtyExtension(
|
||||
Array.from(map.values()).some((extension) => extension.dirty),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (prev && prev.dirty === ext.dirty && prev.save === ext.save) {
|
||||
return;
|
||||
}
|
||||
map.set(key, ext);
|
||||
// Only recompute the dirty summary when dirty flips — save fn changes
|
||||
// every render are common and should not re-render the toolbar.
|
||||
if (prev?.dirty !== ext.dirty) {
|
||||
setHasDirtyExtension(
|
||||
Array.from(map.values()).some((extension) => extension.dirty),
|
||||
);
|
||||
if (ext.dirty) {
|
||||
if (ext.payload !== undefined) pendingRef.current.set(key, ext.payload);
|
||||
} else if (ext.payload != null) {
|
||||
// Clean *and* loaded means the user reverted, so the pending edit goes.
|
||||
// A null payload means the page is still fetching and has nothing to
|
||||
// say yet — dropping the pending edit there would delete it during the
|
||||
// very remount it is supposed to survive.
|
||||
pendingRef.current.delete(key);
|
||||
}
|
||||
syncPendingKeys();
|
||||
},
|
||||
[syncPendingKeys],
|
||||
);
|
||||
|
||||
/** A payload this page left behind earlier in the session, if any. */
|
||||
const pendingExtensionPayload = useCallback(
|
||||
(key: string) => pendingRef.current.get(key),
|
||||
[],
|
||||
);
|
||||
|
||||
const clearPending = useCallback(() => {
|
||||
pendingRef.current.clear();
|
||||
syncPendingKeys();
|
||||
}, [syncPendingKeys]);
|
||||
|
||||
const [settingsError, setSettingsError] = useState<string | null>(null);
|
||||
|
||||
// Single load step. Kept separate from the mount effect so a "Retry" action
|
||||
@@ -745,6 +804,34 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
if (payload.providers) setProviders(payload.providers);
|
||||
if (payload.connection_targets)
|
||||
setConnectionTargets(payload.connection_targets);
|
||||
|
||||
// A draft parked in an earlier session takes over the editable copy —
|
||||
// otherwise "Save Draft" would look like it had done nothing at all.
|
||||
try {
|
||||
const draftResponse = await apiFetch(apiUrl("/api/v1/settings/draft"));
|
||||
if (draftResponse.ok) {
|
||||
const stored = (await draftResponse.json()) as {
|
||||
draft: StoredDraft | null;
|
||||
};
|
||||
if (stored.draft) {
|
||||
setStoredDraft(stored.draft);
|
||||
if (stored.draft.catalog) setDraft(cloneCatalog(stored.draft.catalog));
|
||||
for (const [key, value] of Object.entries(
|
||||
stored.draft.extensions ?? {},
|
||||
)) {
|
||||
pendingRef.current.set(key, value);
|
||||
}
|
||||
syncPendingKeys();
|
||||
// Pages fetch their own state in parallel with this and may have
|
||||
// already read an empty pending map. Bumping the revision re-runs
|
||||
// their load effect now that the draft is actually here.
|
||||
setDraftRevision((value) => value + 1);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// No draft is the normal case and a failed read must not block the
|
||||
// page; the live settings above are already in hand.
|
||||
}
|
||||
settingsLoaded = true;
|
||||
} catch (err) {
|
||||
console.error("Failed to load settings:", err);
|
||||
@@ -775,7 +862,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
);
|
||||
}
|
||||
}
|
||||
}, [t]);
|
||||
}, [syncPendingKeys, t]);
|
||||
|
||||
// Load settings + status once on mount. Subsequent navigations between
|
||||
// settings sub-pages share this state via the layout-level provider.
|
||||
@@ -804,6 +891,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
return () => clearTimeout(timer);
|
||||
}, [toast]);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
window.sessionStorage.setItem(
|
||||
@@ -1305,43 +1393,75 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
}, [llmContextDetection, mutateCatalog, t]);
|
||||
|
||||
// ── Save / Apply ────────────────────────────────────────────────────────
|
||||
const saveCatalog = useCallback(async () => {
|
||||
if (!catalogEditable) return;
|
||||
/** The envelope the draft endpoint stores: catalog plus every pending page. */
|
||||
const draftEnvelope = useCallback(
|
||||
() => ({
|
||||
catalog: catalogEditable ? draft : null,
|
||||
extensions: Object.fromEntries(pendingRef.current.entries()),
|
||||
}),
|
||||
[catalogEditable, draft],
|
||||
);
|
||||
|
||||
/**
|
||||
* Save Draft — write everything unsaved to the draft store and stop there.
|
||||
*
|
||||
* Nothing here reaches the files the runtime resolves against, which is the
|
||||
* entire difference from Apply. It covers the pages that keep state outside
|
||||
* the catalog too; previously this button only ever wrote the catalog and
|
||||
* reported success for edits it had not touched.
|
||||
*/
|
||||
const saveDraft = useCallback(async () => {
|
||||
setSaving(true);
|
||||
const signature = envelopeSignatureRef.current;
|
||||
try {
|
||||
const response = await apiFetch(apiUrl("/api/v1/settings/catalog"), {
|
||||
const response = await apiFetch(apiUrl("/api/v1/settings/draft"), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ catalog: draft }),
|
||||
body: JSON.stringify(draftEnvelope()),
|
||||
});
|
||||
const payload = await response.json();
|
||||
setCatalog(payload.catalog);
|
||||
setDraft(cloneCatalog(payload.catalog));
|
||||
// The model list the chat composer shows is derived from this catalog.
|
||||
invalidateLLMOptionsCache();
|
||||
setToast(t("Draft saved"));
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const payload = (await response.json()) as { draft: StoredDraft | null };
|
||||
setStoredDraft(payload.draft ?? null);
|
||||
setSavedSignature(signature);
|
||||
setToast(t("Draft saved — not applied yet"));
|
||||
} catch (err) {
|
||||
setToast(
|
||||
t("Could not save the draft: {{message}}", {
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [catalogEditable, draft, t]);
|
||||
}, [draftEnvelope, t]);
|
||||
|
||||
/** Apply — move everything into the live files and clear the draft. */
|
||||
const applyCatalog = useCallback(async () => {
|
||||
setApplying(true);
|
||||
try {
|
||||
// Flush extensions (e.g. /settings/memory) first so their saved
|
||||
// state is visible to any backend side-effects in /apply below.
|
||||
const exts = Array.from(extensionsRef.current.values()).filter(
|
||||
(e) => e.dirty,
|
||||
);
|
||||
await Promise.all(exts.map((e) => e.save()));
|
||||
// Park the current state server-side first so Apply promotes exactly
|
||||
// what is on screen, and so credentials typed into a draft never have
|
||||
// to round-trip through the browser as placeholders.
|
||||
await apiFetch(apiUrl("/api/v1/settings/draft"), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(draftEnvelope()),
|
||||
});
|
||||
|
||||
// Pages still on screen save themselves — they refresh their own local
|
||||
// state and surface their own errors. Everything else pending is
|
||||
// written straight to the endpoint that owns it.
|
||||
const mounted = extensionsRef.current;
|
||||
for (const [key, payload] of pendingRef.current.entries()) {
|
||||
const ext = mounted.get(key);
|
||||
if (ext?.dirty) await ext.save();
|
||||
else await applyExtensionPayload(key, payload);
|
||||
}
|
||||
|
||||
// The catalog apply is only meaningful when editable; an extension-
|
||||
// only flush should still produce a success toast.
|
||||
if (catalogEditable) {
|
||||
const response = await apiFetch(apiUrl("/api/v1/settings/apply"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ catalog: draft }),
|
||||
});
|
||||
const payload = await response.json();
|
||||
setCatalog(payload.catalog);
|
||||
@@ -1349,12 +1469,41 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
invalidateLLMOptionsCache();
|
||||
const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));
|
||||
setStatus((await statusResponse.json()) as SystemStatus);
|
||||
} else {
|
||||
await apiFetch(apiUrl("/api/v1/settings/draft"), { method: "DELETE" });
|
||||
}
|
||||
setToast(t("All changes saved"));
|
||||
clearPending();
|
||||
setStoredDraft(null);
|
||||
setSavedSignature(null);
|
||||
setToast(t("Applied"));
|
||||
} catch (err) {
|
||||
setToast(
|
||||
t("Could not apply: {{message}}", {
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setApplying(false);
|
||||
}
|
||||
}, [catalogEditable, draft, t]);
|
||||
}, [catalogEditable, clearPending, draftEnvelope, t]);
|
||||
|
||||
/** Throw the draft away and go back to what is actually live. */
|
||||
const discardDraft = useCallback(async () => {
|
||||
setApplying(true);
|
||||
try {
|
||||
await apiFetch(apiUrl("/api/v1/settings/draft"), { method: "DELETE" });
|
||||
clearPending();
|
||||
setStoredDraft(null);
|
||||
setSavedSignature(null);
|
||||
setDraft(cloneCatalog(catalog));
|
||||
setToast(t("Draft discarded"));
|
||||
// Pages holding their own copy of a discarded payload have to re-read.
|
||||
setDraftRevision((value) => value + 1);
|
||||
} finally {
|
||||
setApplying(false);
|
||||
}
|
||||
}, [catalog, clearPending, t]);
|
||||
|
||||
|
||||
// ── Diagnostics ─────────────────────────────────────────────────────────
|
||||
// Reset capability snapshot when switching embedding profile/model so a
|
||||
@@ -1568,13 +1717,50 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
}, [tourStepIndex, router]);
|
||||
|
||||
// ── Derived ─────────────────────────────────────────────────────────────
|
||||
const hasUnsavedChanges = useMemo(() => {
|
||||
return (
|
||||
hasDirtyExtension ||
|
||||
// What the current screen state would be persisted as. Compared against the
|
||||
// last thing actually written so the toolbar can tell "not saved anywhere"
|
||||
// apart from "saved as a draft, not applied".
|
||||
const envelopeSignature = useMemo(
|
||||
() =>
|
||||
JSON.stringify({
|
||||
catalog: catalogEditable ? draft : null,
|
||||
extensions: pendingSignature,
|
||||
}),
|
||||
[catalogEditable, draft, pendingSignature],
|
||||
);
|
||||
|
||||
const differsFromLive = useMemo(
|
||||
() =>
|
||||
pendingSignature !== "{}" ||
|
||||
(catalogEditable === true &&
|
||||
JSON.stringify(catalog) !== JSON.stringify(draft))
|
||||
);
|
||||
}, [catalog, catalogEditable, draft, hasDirtyExtension]);
|
||||
JSON.stringify(catalog) !== JSON.stringify(draft)),
|
||||
[catalog, catalogEditable, draft, pendingSignature],
|
||||
);
|
||||
|
||||
const envelopeSignatureRef = useRef(envelopeSignature);
|
||||
envelopeSignatureRef.current = envelopeSignature;
|
||||
|
||||
const draftState: DraftState = !differsFromLive
|
||||
? "clean"
|
||||
: envelopeSignature === savedSignature
|
||||
? "saved"
|
||||
: "unsaved";
|
||||
|
||||
const hasUnsavedChanges = draftState === "unsaved";
|
||||
|
||||
// Moving between settings pages keeps unsaved edits (they live on the
|
||||
// provider), but closing or reloading the tab cannot — that is the moment
|
||||
// the work would disappear, so warn there. Only for edits with nowhere to
|
||||
// fall back to: once saved as a draft the server already has them.
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) return;
|
||||
const warn = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
event.returnValue = "";
|
||||
};
|
||||
window.addEventListener("beforeunload", warn);
|
||||
return () => window.removeEventListener("beforeunload", warn);
|
||||
}, [hasUnsavedChanges]);
|
||||
|
||||
const settingsLoading = catalogEditable === null;
|
||||
|
||||
@@ -1625,8 +1811,13 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
applyDetectedContextWindow,
|
||||
saving,
|
||||
applying,
|
||||
saveCatalog,
|
||||
saveDraft,
|
||||
applyCatalog,
|
||||
discardDraft,
|
||||
storedDraft,
|
||||
draftState,
|
||||
draftRevision,
|
||||
pendingExtensionPayload,
|
||||
registerExtension,
|
||||
logs,
|
||||
testRunning,
|
||||
@@ -1646,6 +1837,11 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
applyDetectedContextWindow,
|
||||
applyCatalog,
|
||||
applying,
|
||||
draftState,
|
||||
storedDraft,
|
||||
draftRevision,
|
||||
pendingExtensionPayload,
|
||||
discardDraft,
|
||||
catalog,
|
||||
catalogEditable,
|
||||
codeBlockShowLineNumbers,
|
||||
@@ -1674,7 +1870,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
removeActiveModel,
|
||||
removeActiveProfile,
|
||||
runDetailedTest,
|
||||
saveCatalog,
|
||||
saveDraft,
|
||||
saving,
|
||||
settingsError,
|
||||
loadSettings,
|
||||
|
||||
@@ -1,30 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2, Rocket, Save, Wand2 } from "lucide-react";
|
||||
import { Loader2, Rocket, Save, Undo2, Wand2 } from "lucide-react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { storagePathFor } from "@/lib/settings-nav";
|
||||
import { useSettings } from "./SettingsContext";
|
||||
|
||||
// Sticky toolbar above the sub-page content. Save Draft / Apply only show
|
||||
// when there's actually something to save — keeps the bar quiet for the
|
||||
// majority of sessions that just visit Appearance.
|
||||
/**
|
||||
* Sticky toolbar above the sub-page content.
|
||||
*
|
||||
* Save Draft and Apply now promise different things and the bar has to say
|
||||
* which state you are in, because "there is a draft waiting" is invisible
|
||||
* otherwise — a draft parked yesterday would sit there unexplained.
|
||||
*
|
||||
* unsaved edits → Save draft · Apply ("Unsaved changes")
|
||||
* draft on server → Apply · Discard ("Draft not applied yet")
|
||||
* neither → nothing to do ("All changes saved")
|
||||
*
|
||||
* The storage path moved into the status line's tooltip: self-hosted users
|
||||
* occasionally want to know which file backs a page, but it is a developer
|
||||
* fact and does not belong permanently on screen for everyone else.
|
||||
*/
|
||||
export function SettingsToolbar() {
|
||||
const { t } = useTranslation();
|
||||
const pathname = usePathname() ?? "";
|
||||
const storagePath = storagePathFor(pathname);
|
||||
const {
|
||||
catalogEditable,
|
||||
hasUnsavedChanges,
|
||||
draftState,
|
||||
saving,
|
||||
applying,
|
||||
saveCatalog,
|
||||
saveDraft,
|
||||
applyCatalog,
|
||||
discardDraft,
|
||||
startTour,
|
||||
toast,
|
||||
} = useSettings();
|
||||
|
||||
const busy = saving || applying;
|
||||
const canApply = draftState !== "clean";
|
||||
|
||||
if (catalogEditable !== true) {
|
||||
if (!toast) return null;
|
||||
return (
|
||||
@@ -36,31 +52,30 @@ export function SettingsToolbar() {
|
||||
);
|
||||
}
|
||||
|
||||
const status = toast
|
||||
? { text: toast, tone: "text-[var(--primary)] animate-fade-in" }
|
||||
: draftState === "unsaved"
|
||||
? {
|
||||
text: t("Unsaved changes"),
|
||||
tone: "text-amber-600 dark:text-amber-400",
|
||||
}
|
||||
: draftState === "saved"
|
||||
? {
|
||||
text: t("Draft not applied yet"),
|
||||
tone: "text-amber-600 dark:text-amber-400",
|
||||
}
|
||||
: {
|
||||
text: t("All changes saved"),
|
||||
tone: "text-[var(--muted-foreground)]",
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-3 px-1 py-2">
|
||||
<p
|
||||
className={`min-w-0 truncate text-[12px] ${
|
||||
toast
|
||||
? "text-[var(--primary)] animate-fade-in"
|
||||
: hasUnsavedChanges
|
||||
? "text-amber-600 dark:text-amber-400"
|
||||
: "text-[var(--muted-foreground)]"
|
||||
}`}
|
||||
className={`min-w-0 truncate text-[12px] ${status.tone}`}
|
||||
title={storagePath || undefined}
|
||||
>
|
||||
{toast ? (
|
||||
toast
|
||||
) : hasUnsavedChanges ? (
|
||||
t("Draft has unsaved changes")
|
||||
) : storagePath ? (
|
||||
<>
|
||||
{t("Saved to")}{" "}
|
||||
<span className="font-mono text-[var(--foreground)]/65">
|
||||
{storagePath}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
t("All changes saved")
|
||||
)}
|
||||
{status.text}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
@@ -70,9 +85,21 @@ export function SettingsToolbar() {
|
||||
<Rocket className="h-3 w-3" />
|
||||
{t("Tour")}
|
||||
</button>
|
||||
{canApply && (
|
||||
<button
|
||||
onClick={discardDraft}
|
||||
disabled={busy}
|
||||
title={t("Go back to what is currently live.")}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
|
||||
>
|
||||
<Undo2 className="h-3 w-3" />
|
||||
{t("Discard")}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={saveCatalog}
|
||||
disabled={saving || !hasUnsavedChanges}
|
||||
onClick={saveDraft}
|
||||
disabled={busy || draftState !== "unsaved"}
|
||||
title={t("Store these changes without putting them into effect.")}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
|
||||
>
|
||||
{saving ? (
|
||||
@@ -80,12 +107,13 @@ export function SettingsToolbar() {
|
||||
) : (
|
||||
<Save className="h-3 w-3" />
|
||||
)}
|
||||
{t("Save Draft")}
|
||||
{t("Save draft")}
|
||||
</button>
|
||||
<button
|
||||
data-tour="tour-actions"
|
||||
onClick={applyCatalog}
|
||||
disabled={applying}
|
||||
disabled={busy || !canApply}
|
||||
title={t("Put these settings into effect.")}
|
||||
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"
|
||||
>
|
||||
{applying ? (
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { apiFetch, apiUrl } from "@/lib/api";
|
||||
|
||||
/**
|
||||
* Settings pages that keep state outside the model catalog.
|
||||
*
|
||||
* Each one registers with `registerExtension(key, …)` under the key below and
|
||||
* saves by PUT-ing its own payload to the matching endpoint. The table exists
|
||||
* so a draft can be applied for a page that is not on screen: the user edits
|
||||
* Starting points, navigates to LLM, and presses Apply — nothing is mounted to
|
||||
* run that page's own save closure any more, but its drafted payload is still
|
||||
* pending and has to land somewhere.
|
||||
*
|
||||
* The pages import their URL from here rather than writing it twice, so the
|
||||
* two paths cannot drift apart.
|
||||
*/
|
||||
export const EXTENSION_ENDPOINTS = {
|
||||
"chat-starters": "/api/v1/settings/chat-starters",
|
||||
"chat-attachments": "/api/v1/settings/chat-attachments",
|
||||
"chat-timeout": "/api/v1/settings/chat-response-timeout",
|
||||
capabilities: "/api/v1/capabilities/settings",
|
||||
memory: "/api/v1/memory/settings",
|
||||
network: "/api/v1/settings/network",
|
||||
} as const;
|
||||
|
||||
export type ExtensionKey = keyof typeof EXTENSION_ENDPOINTS;
|
||||
|
||||
export function isExtensionKey(value: string): value is ExtensionKey {
|
||||
return value in EXTENSION_ENDPOINTS;
|
||||
}
|
||||
|
||||
/** Write one drafted payload to the endpoint that owns it. */
|
||||
export async function applyExtensionPayload(
|
||||
key: string,
|
||||
payload: unknown,
|
||||
): Promise<void> {
|
||||
if (!isExtensionKey(key) || payload == null) return;
|
||||
const response = await apiFetch(apiUrl(EXTENSION_ENDPOINTS[key]), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`${key}: HTTP ${response.status}`);
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -3604,5 +3604,15 @@
|
||||
"Configured {{count}} services and made them active.": "Configured {{count}} services and made them active.",
|
||||
"Configured {{count}} services — {{kept}} kept your existing choice.": "Configured {{count}} services — {{kept}} kept your existing choice.",
|
||||
"Opened from Connections. Applying will also make this the {{service}} profile in use.": "Opened from Connections. Applying will also make this the {{service}} profile in use.",
|
||||
"Back to {{name}}": "Back to {{name}}"
|
||||
"Back to {{name}}": "Back to {{name}}",
|
||||
"Save draft": "Save draft",
|
||||
"Draft not applied yet": "Draft not applied yet",
|
||||
"Draft saved — not applied yet": "Draft saved — not applied yet",
|
||||
"Draft discarded": "Draft discarded",
|
||||
"Applied": "Applied",
|
||||
"Store these changes without putting them into effect.": "Store these changes without putting them into effect.",
|
||||
"Put these settings into effect.": "Put these settings into effect.",
|
||||
"Go back to what is currently live.": "Go back to what is currently live.",
|
||||
"Could not save the draft: {{message}}": "Could not save the draft: {{message}}",
|
||||
"Could not apply: {{message}}": "Could not apply: {{message}}"
|
||||
}
|
||||
|
||||
+11
-1
@@ -3604,5 +3604,15 @@
|
||||
"Configured {{count}} services and made them active.": "已配置 {{count}} 个服务并设为当前使用。",
|
||||
"Configured {{count}} services — {{kept}} kept your existing choice.": "已配置 {{count}} 个服务;{{kept}} 保留了你原有的选择。",
|
||||
"Opened from Connections. Applying will also make this the {{service}} profile in use.": "从「连接」跳转而来。应用后,{{service}} 将改用这个配置。",
|
||||
"Back to {{name}}": "改回 {{name}}"
|
||||
"Back to {{name}}": "改回 {{name}}",
|
||||
"Save draft": "存草稿",
|
||||
"Draft not applied yet": "草稿尚未应用",
|
||||
"Draft saved — not applied yet": "草稿已保存,尚未应用",
|
||||
"Draft discarded": "已放弃草稿",
|
||||
"Applied": "已应用",
|
||||
"Store these changes without putting them into effect.": "保存这些更改,但先不生效。",
|
||||
"Put these settings into effect.": "让这些设置生效。",
|
||||
"Go back to what is currently live.": "回到当前生效的设置。",
|
||||
"Could not save the draft: {{message}}": "草稿保存失败:{{message}}",
|
||||
"Could not apply: {{message}}": "应用失败:{{message}}"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user