Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(studio): edit startup configuration and support ROOT restart (#5730)
yufeng4c9a755bff4d
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex fb6565eca..79c406d96 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -496,6 +496,7 @@ This catalog follows the routes actually mounted by the server. Each group headi|--------|------|-------------|| GET | `/api/v1/admin/configuration` | Get explicit Cluster runtime configuration || PATCH | `/api/v1/admin/configuration` | Update Cluster runtime configuration |+| POST | `/api/v1/admin/restart` | Request a graceful restart of a supported server process (ROOT only) || GET | `/api/v1/admin/accounts/{account_id}/configuration` | Get explicit Account runtime configuration || PATCH | `/api/v1/admin/accounts/{account_id}/configuration` | Update Account runtime configuration || GET | `/api/v1/admin/agent-evolution` | Get Agent Evolution status (deprecated) |diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex e3de7d3c4..b8c1355de 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -534,6 +534,75 @@ Consumer failures are logged without rolling back the persisted override, soa successful response confirms the configuration update but does not certifythat every derived client has applied it. See [runtime configuration source and reload behavior](../guides/01-configuration.md#runtime-configuration-source).+File-mode saves require the complete `content` and the previous `revision`.+Draft previews (`source=file&dry_run=true`) accept optional VLM/Embedding form `settings`;+other sections remain editable through the complete file.+File reads and previews return `form_readonly: true` when the document contains dollar signs, Windows `%VAR%` references, or escaped dollar/percent signs. Model form data is omitted and form patches are rejected. Use file mode to edit the original text, including quoted and unquoted environment references. Validation follows startup expansion of the original text; saves do not serialize the document. CLI startup arguments are reapplied during validation, as during restart.++#### Server Restart++Only ROOT can restart a single-worker `openviking-server` CLI process.+Multi-worker and embedded ASGI launch modes do not support remote restart.++```http+POST /api/v1/admin/restart+Content-Type: application/json+X-API-Key: <root-api-key>++{"revision": "<saved-file-revision>"}+```++`revision` is a required, non-empty string. Obtain the current file revision and+restart capability from `GET /api/v1/admin/configuration?source=file`;+`result.restart` contains `supported`, `instance_id`, and `restarting`.+The restart endpoint does not save configuration. Save any changes first using+`PATCH /api/v1/admin/configuration?source=file`, with `content` and the previous+`revision`, then submit the returned revision to the restart endpoint.++The server checks the current file revision and validates the configuration before+accepting the restart. A stale revision or invalid file returns `INVALID_ARGUMENT`;+an unsupported launch mode or unreadable file returns `FAILED_PRECONDITION`.+No restart is requested when these checks fail.++An accepted request returns **HTTP 202**, before graceful shutdown:++```json+{+ "status": "ok",+ "result": {+ "supported": true,+ "instance_id": "current-instance-id",+ "restarting": true+ }+}+```++The CLI drains active requests, stops its managed Bot, and replaces the process+with the original interpreter, arguments, environment, and working directory.+File saves are rejected once restart has been requested. HTTP 202 confirms+acceptance, not successful recovery: poll the file configuration endpoint until+`instance_id` changes and `restarting` is false. External dependencies may still+prevent startup. If the address, port, or ROOT credential changes, update the+client connection before polling. See [server configuration](../configuration/01-server.md).++Before accepting a restart, the CLI saves the exact file bytes loaded by the+running process in a separate private recovery backup (0600, containing sensitive+configuration). If the new process fails while loading configuration, starting+the Bot, initializing the application, or binding its port, it atomically restores+the previous running configuration and starts again once. The recovered instance+returns `result.restart.rolled_back: true`; Studio reports the rollback.+The recovery backup is deleted after application startup and socket binding succeed.+Subsequent runtime failures do not trigger rollback. Remote restart cannot switch+to multiple workers; use the deployment platform for that change.++This recovery backup differs from `.studio.bak`, which only contains the file+before the most recent save and may never have started successfully. Recovery+only restores the configuration file, not storage or external side effects.+It does not handle stalled startup, forced process termination, or machine failure.+External file changes after restart prevent automatic restoration. If the restored+configuration also fails to start, no further retry occurs; an administrator must+recover the service on the server.+#### Account Configuration ReferenceInitialize Account configuration through `settings` on the create endpoint,diff --git a/docs/en/configuration/01-server.md b/docs/en/configuration/01-server.mdindex 20e700016..9ff2f9862 100644--- a/docs/en/configuration/01-server.md+++ b/docs/en/configuration/01-server.md@@ -17,6 +17,12 @@ openviking-server --config /path/to/ov.confThe server reads the file at startup. Restart the server after changing models, retrieval, storage, or `server` settings, then run `openviking-server doctor`.+Studio's **Server configuration** page offers **Save and restart** for a single-worker `openviking-server` process. The existing ROOT-only `GET /api/v1/admin/configuration?source=file` includes restart capability and instance identity. Only ROOT can request a restart (`POST /api/v1/admin/restart`, body `{"revision":"<saved file revision>"}`). The server validates the current file and its revision, returns HTTP 202, drains active requests, stops its managed Bot, then replaces itself using the original interpreter, arguments, environment and working directory. Studio waits for a new service instance before reporting success. **Save configuration** alone continues to save without restarting.++Multi-worker or embedded ASGI applications report restart as unsupported; restart these through the deployment platform. Startup can still fail because of external dependencies even after schema validation. If the address, port or ROOT credential changes, update Studio's connection settings to reconnect. Account and cluster overrides continue to take precedence over file defaults.++Configurations containing environment references are read-only in the Studio form. Use file mode to edit the original text; quoted/unquoted references, escapes and formatting are saved as submitted. Windows `%VAR%` references and dollar/percent literals (including `\u0024` and `\u0025`) also use file mode to avoid introducing new references during form serialization.+## Configuration StructureThis outline shows common top-level groups, not a runnable configuration. For a first deployment, start with the [minimal example](#minimal-example) and supply your models and credentials. Merge later snippets into the same `ov.conf`.diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 370a6553e..d782b9a17 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -53,6 +53,36 @@ Create `~/.openviking/ov.conf` in your home configuration directory:For `provider: "openai-codex"`, `vlm.api_key` is optional when Codex OAuth is already available.+### Ordered credentials in ov.conf++`vlm` and `query_planner` support an ordered `credentials` array. Embedding supports the same array inside each configured `dense`, `sparse`, or `hybrid` section. Index 0 has the highest priority; later entries provide failover credentials. The model sections remain JSON objects, and existing single-credential configurations remain supported.++Merge the following fields into your `ov.conf`; set `PRIMARY_API_KEY` and `BACKUP_API_KEY` before starting the server:++```json+{+ "vlm": {+ "model": "your-vlm-model",+ "credentials": [+ {"id": "primary", "provider": "openai", "api_key": "${PRIMARY_API_KEY}"},+ {"id": "backup", "provider": "openai", "api_key": "${BACKUP_API_KEY}"}+ ]+ },+ "embedding": {+ "dense": {+ "model": "text-embedding-3-small",+ "dimension": 1536,+ "credentials": [+ {"id": "primary", "provider": "openai", "api_key": "${PRIMARY_API_KEY}"},+ {"id": "backup", "provider": "openai", "api_key": "${BACKUP_API_KEY}"}+ ]+ }+ }+}+```++Each credential can specify its own provider, model and connection fields; an omitted model uses the parent section's `model`. Embedding credentials must remain compatible with the parent model's vector dimension and input semantics. `query_planner.credentials` follows the VLM format. Rerank remains a single configuration and does not support a `credentials` array.+## Configuration Scope and Update LifecycleOpenViking configuration has two layers:diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex baed385fa..39d6406b7 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -491,6 +491,7 @@ JSON 输出 - 错误:|------|------|------|| GET | `/api/v1/admin/configuration` | 获取 Cluster 层显式运行时配置 || PATCH | `/api/v1/admin/configuration` | 更新 Cluster 层运行时配置 |+| POST | `/api/v1/admin/restart` | 请求支持该能力的服务进程优雅重启(仅 ROOT) || GET | `/api/v1/admin/accounts/{account_id}/configuration` | 获取 Account 层显式运行时配置 || PATCH | `/api/v1/admin/accounts/{account_id}/configuration` | 更新 Account 层运行时配置 || GET | `/api/v1/admin/agent-evolution` | 获取 Agent 进化状态(deprecated) |diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex b1ef6d25c..680ecd75c 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -445,6 +445,67 @@ PATCH 会先做结构校验,再构造合并后的配置:未知路径和运匹配的进程内 Consumer;Consumer 失败会记录日志但不会回滚已持久化的配置,因此接口成功只表示配置层更新成功,不保证所有派生客户端都已完成切换。配置存储和重载行为见[运行时配置来源与重载行为](../guides/01-configuration.md#runtime-configuration-source)。+文件保存始终提交完整 `content` 和旧 `revision`。+草稿预览(`source=file&dry_run=true`)可附带 VLM/Embedding 表单 `settings`;+其他配置节通过完整文件编辑。++文件含美元符号、Windows `%VAR%` 引用或转义的美元/百分号时,读取和预览返回 `form_readonly: true`,不返回模型表单数据,并拒绝表单修改。请使用文件模式编辑原文,包括带引号和未带引号的环境变量引用。验证沿用启动时对原文展开环境变量的流程,保存不会重新序列化文档。文件校验会应用 CLI 启动参数覆盖,与重启时的处理一致。++#### 服务端重启++仅 ROOT 可以重启通过单 worker `openviking-server` CLI 启动的进程。+多 worker 和嵌入式 ASGI 启动模式不支持远程重启。++```http+POST /api/v1/admin/restart+Content-Type: application/json+X-API-Key: <root-api-key>++{"revision": "<已保存文件的版本>"}+```++`revision` 是必填的非空字符串。通过+`GET /api/v1/admin/configuration?source=file` 获取当前文件版本和重启能力;+`result.restart` 包含 `supported`、`instance_id` 和 `restarting`。+重启接口不保存配置。修改配置时,先通过+`PATCH /api/v1/admin/configuration?source=file` 提交 `content` 和旧 `revision`,+再将保存响应中的新版本提交给重启接口。++服务端接受重启前会核对当前文件版本并校验配置。+版本过期或文件无效返回 `INVALID_ARGUMENT`;启动模式不支持或文件不可读返回+`FAILED_PRECONDITION`。这些检查失败时不会请求重启。++接受请求后,在优雅关闭前返回 **HTTP 202**:++```json+{+ "status": "ok",+ "result": {+ "supported": true,+ "instance_id": "current-instance-id",+ "restarting": true+ }+}+```++CLI 等待现有请求结束,停止其管理的 Bot,再使用原解释器、启动参数、环境变量和+工作目录替换当前进程。接受重启后拒绝文件保存请求。HTTP 202 只表示请求已接受,+不代表服务已恢复;应轮询文件配置读取接口,直到 `instance_id` 改变且+`restarting` 为 false。外部依赖仍可能阻止启动。如果地址、端口或 ROOT 凭证发生+变化,需要先更新客户端连接设置再轮询。详见[服务端配置](../configuration/01-server.md)。++CLI 在接受重启前保存当前进程启动时实际加载的文件原文,作为独立的私有恢复备份+(0600,包含敏感配置)。新进程在配置加载、Bot 启动、应用初始化或监听端口时失败,+会原子恢复此前运行的配置并重新启动一次;恢复后的配置读取响应中+`result.restart.rolled_back` 为 true,Studio 会提示已回滚。+应用初始化和端口绑定成功后删除恢复备份,不对后续运行期故障自动回滚。+远程重启不能切换为多 worker;应通过部署平台执行这种变更。++恢复备份与每次保存生成的 `.studio.bak` 不同:后者仅保留上一次保存前的文件,+未必曾成功启动。自动恢复只回滚配置文件,不撤销存储或外部系统中的副作用,+也不处理启动卡死、进程被强制终止或机器故障。若重启后文件被外部修改,拒绝覆盖;+若恢复后的配置仍无法启动,不再重试,需要管理员在服务器上恢复服务。+#### Account Configuration 接口参考Account 配置通过创建接口的 `settings` 初始化,并通过 configuration 接口读取和更新:diff --git a/docs/zh/configuration/01-server.md b/docs/zh/configuration/01-server.mdindex ad0bad06b..32ac23f79 100644--- a/docs/zh/configuration/01-server.md+++ b/docs/zh/configuration/01-server.md@@ -17,6 +17,12 @@ openviking-server --config /path/to/ov.conf服务端启动时读取配置。修改模型、检索、存储或 `server` 配置后,需要重启服务;重启后建议运行 `openviking-server doctor`。+通过单 worker 的 `openviking-server` 启动时,Studio 的「服务端配置」页面提供「保存并重启」。重启能力和实例标识复用现有 ROOT 配置读取接口(`GET /api/v1/admin/configuration?source=file`)返回;只有 ROOT 可以请求重启(`POST /api/v1/admin/restart`,请求体为 `{"revision":"<已保存文件的版本>"}`)。服务校验当前文件和版本后返回 HTTP 202,等待现有请求结束,停止其管理的 Bot,再使用原解释器、启动参数、环境变量和工作目录替换当前进程。页面确认新的服务实例恢复后才显示成功。单独点击「保存配置」仍只保存文件。++多 worker 或嵌入式 ASGI 启动不支持页面重启,需要通过部署平台重启。配置通过校验后,外部依赖仍可能导致启动失败。如果修改了地址、端口或 ROOT 凭证,请更新 Studio 连接设置。账号和集群覆盖配置仍优先于文件默认配置。++配置含环境变量引用时,Studio 表单只读,请使用文件模式编辑原文。带引号或未带引号的引用、转义和格式按提交内容保存。Windows `%VAR%` 引用和美元/百分号字面值(包括 `\u0024`、`\u0025`)也使用文件模式,避免表单序列化引入新的引用。+## 配置结构下面只展示常用顶层分组,不是可直接运行的完整配置。首次启动可从本页的[最小示例](#最小示例)开始,填写实际模型与凭据;后续示例中的片段应合并到同一个 `ov.conf`。diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex 21a03d8cc..2e0d2cd0b 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -54,6 +54,36 @@ openviking-server doctor如果 `provider` 是 `openai-codex`,并且 Codex OAuth 已经就绪,则 `vlm.api_key` 可以省略。+### ov.conf 的有序凭据数组++`vlm` 和 `query_planner` 支持有序的 `credentials` 数组;Embedding 在已配置的 `dense`、`sparse` 或 `hybrid` 节内支持同样的数组。索引 0 优先级最高,后续元素提供故障切换凭据。模型配置节仍是 JSON 对象,原有单凭据配置继续兼容。++将以下字段合并到你的 `ov.conf`,并在启动服务前设置 `PRIMARY_API_KEY` 和 `BACKUP_API_KEY`:++```json+{+ "vlm": {+ "model": "your-vlm-model",+ "credentials": [+ {"id": "primary", "provider": "openai", "api_key": "${PRIMARY_API_KEY}"},+ {"id": "backup", "provider": "openai", "api_key": "${BACKUP_API_KEY}"}+ ]+ },+ "embedding": {+ "dense": {+ "model": "text-embedding-3-small",+ "dimension": 1536,+ "credentials": [+ {"id": "primary", "provider": "openai", "api_key": "${PRIMARY_API_KEY}"},+ {"id": "backup", "provider": "openai", "api_key": "${BACKUP_API_KEY}"}+ ]+ }+ }+}+```++每项凭据可以独立指定 provider、模型及连接字段;未指定模型时使用父级的 `model`。Embedding 凭据必须与父级模型的向量维度和输入语义兼容。`query_planner.credentials` 使用与 VLM 相同的格式。Rerank 仍使用单配置,不支持 `credentials` 数组。+## 配置范围与生效方式OpenViking 的配置分为两个层级:diff --git a/openviking/config/config_file.py b/openviking/config/config_file.pynew file mode 100644index 000000000..8a000bbff--- /dev/null+++ b/openviking/config/config_file.py@@ -0,0 +1,318 @@+"""Versioned, atomic edits to the actual startup configuration file."""++import hashlib+import json+import os+import re+import stat+import sys+import tempfile+from contextlib import contextmanager+from pathlib import Path++from openviking_cli.utils.config.embedding_config import EmbeddingCredential+from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+)+from openviking_cli.utils.config.vlm_config import VLMConfig, VLMCredential++FORM_MODEL_KINDS = ("vlm", "embedding")+# Reserve environment references for the verbatim file editor on every platform.+# Escaped dollars/percents must stay literal when startup expands the original text.+_FORM_REFERENCE = re.compile(r"\$|%[^%]+%|\\u002[45]", re.IGNORECASE)+++def _form_readonly(content: str) -> bool:+ return bool(_FORM_REFERENCE.search(content))+++def _provider_source(original: dict, provider: str | None) -> dict:+ return next(+ (+ config+ for name, config in (original.get("providers") or {}).items()+ if name.strip().lower() == (provider or "").strip().lower()+ ),+ {},+ )+++def _binding_values(binding, parent, embedding: bool, original: dict, index: int) -> dict:+ values = (+ {+ key: value+ for key in EmbeddingCredential.model_fields+ if (value := getattr(binding, key, None) or getattr(parent, key, None)) is not None+ }+ if embedding+ else binding.model_dump(exclude_none=True)+ )+ explicit = original.get("credentials") or []+ source = explicit[index] if index < len(explicit) else {}+ if not embedding and "model" not in source and (explicit or index == 0):+ # A synthesized primary binding must keep inheriting the shared model.+ values.pop("model", None)+ return values+++def _revision(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _validate(content: str, server_overrides: dict | None = None) -> OpenVikingConfig:+ try:+ from openviking.server.config import ServerConfig, validate_server_config++ expanded = json.loads(os.path.expandvars(content.lstrip("\ufeff")))+ server = expanded.get("server")+ server_config = ServerConfig.model_validate({} if server is None else server)+ # The CLI reapplies these arguments after loading ov.conf on every restart.+ if server_overrides:+ server_config = server_config.model_copy(update=server_overrides)+ validate_server_config(server_config)+ return OpenVikingConfig.from_dict(expanded)+ except (Exception, SystemExit) as exc:+ # Startup validators exit on failure; API validation must keep the server alive.+ # Validation errors may contain API keys from rejected input.+ raise ValueError("Invalid ov.conf configuration; check configuration fields") from exc+++def _parse(content: str) -> dict:+ try:+ raw = json.loads(content.lstrip("\ufeff"))+ if not isinstance(raw, dict):+ raise ValueError()+ return raw+ except ValueError as exc:+ raise ValueError("ov.conf must contain a JSON object") from exc+++def _read(path: Path, server_overrides: dict | None = None):+ data = path.read_bytes()+ try:+ content = data.decode("utf-8")+ except UnicodeError as exc:+ raise ValueError("ov.conf must contain UTF-8 JSON") from exc+ config = _validate(content, server_overrides)+ return data, content, config+++def _path() -> Path:+ path = OpenVikingConfigSingleton.get_config_file()+ if path is None:+ raise ValueError("Server was initialized without a configuration file")+ return path+++def _model_view(content: str, config: OpenVikingConfig) -> dict:+ if _form_readonly(content):+ # Never project expanded credentials into the form response.+ return {kind: {"config": {}} for kind in FORM_MODEL_KINDS}+ raw = _parse(content)+ models = {}+ for kind in FORM_MODEL_KINDS:+ model = getattr(config, kind)+ value = model.model_dump(exclude_none=True)+ original = raw.get(kind) or {}+ value = _merge(value, original)+ if kind == "vlm":+ # VLM normalization synthesizes provider maps from parent fields.+ # Return only the explicit map to preserve legacy form bindings.+ value["providers"] = original.get("providers") or {}+ sections = [(value, original, model)]+ if kind == "embedding":+ sections = [+ (value[mode], original.get(mode) or {}, getattr(model, mode))+ for mode in ("dense", "sparse", "hybrid")+ if getattr(model, mode) is not None+ ]+ for section, original_section, section_model in sections:+ bindings = section_model.credentials+ if kind == "embedding" and not bindings:+ bindings = [section_model]+ section["credentials"] = [+ _binding_values(+ binding, section_model, kind == "embedding", original_section, index+ )+ for index, binding in enumerate(bindings)+ ]+ if kind == "embedding":+ for index, binding in enumerate(section["credentials"]):+ if not binding.get("id"):+ binding["id"] = f"credential-{index}"+ models[kind] = {"config": value}+ return models+++def preview_config_file(+ content: str, settings: dict | None = None, server_overrides: dict | None = None+) -> dict:+ """Validate a draft and project its form fields without writing or publishing it."""+ if settings:+ if _form_readonly(content):+ raise ValueError("Configuration with environment references requires file editing")+ raw = _parse(content)+ _apply_model_changes(raw, settings)+ content = json.dumps(raw, ensure_ascii=False, indent=2) + "\n"+ if _form_readonly(content):+ raise ValueError("Environment references must be entered through the file editor")+ config = _validate(content, server_overrides)+ return {+ "content": content,+ "models": _model_view(content, config),+ "form_readonly": _form_readonly(content),+ }+++def read_config_file(server_overrides: dict | None = None) -> dict:+ path = _path()+ data, content, config = _read(path, server_overrides)+ active = OpenVikingConfigSingleton.get_instance()+ startup_revision = OpenVikingConfigSingleton.get_config_file_revision()+ return {+ "content": content,+ "models": _model_view(content, config),+ "form_readonly": _form_readonly(content),+ "revision": _revision(data),+ "file_path": str(path),+ "writable": bool(path.stat().st_mode & 0o222)+ and os.access(path, os.W_OK)+ and os.access(path.parent, os.W_OK),+ "restart_required": (+ _revision(data) != startup_revision+ if startup_revision is not None+ else config.model_dump() != active.model_dump()+ ),+ }+++def _merge(old: dict, changes: dict) -> dict:+ result = dict(old)+ for key, value in changes.items():+ result[key] = (+ _merge(result[key], value)+ if isinstance(value, dict)+ and isinstance(result.get(key), dict)+ and key not in {"extra_headers", "extra_body", "extra_request_body"}+ else value+ )+ return result+++def _merge_credentials(old: dict, changes: dict, embedding: bool) -> dict:+ result = _merge(old, changes)+ if "credentials" not in changes:+ return result+ if not isinstance(changes["credentials"], list) or not all(+ isinstance(binding, dict) for binding in changes["credentials"]+ ):+ return result+ fields = set((EmbeddingCredential if embedding else VLMCredential).model_fields) - {+ "id",+ "model",+ }+ defaults = {}+ if not embedding:+ providers = result.get("providers") or {}+ provider = result.get("provider") or result.get("backend") or result.get("default_provider")+ if not provider and providers:+ legacy = VLMConfig.model_validate({**result, "credentials": []})+ _, provider = legacy.get_provider_config()+ defaults.update(_provider_source(result, provider))+ if provider:+ defaults["provider"] = provider+ defaults.update({key: value for key, value in result.items() if key in fields})+ if embedding and defaults.get("provider") is None and result.get("backend") is not None:+ defaults["provider"] = result["backend"]+ # Materialize inherited bindings before removing legacy fallbacks. Explicit+ # null/empty values must mean clearing, not re-inheriting obsolete secrets.+ defaults = {key: value for key, value in defaults.items() if key in fields}+ result["credentials"] = [_merge(defaults, binding) for binding in changes["credentials"]]+ for key in fields:+ result.pop(key, None)+ result.pop("backend", None)+ if not embedding:+ for key in ("providers", "default_provider", "backup"):+ result.pop(key, None)+ return result+++def _merge_model(old: dict, changes: dict, kind: str) -> dict:+ if kind == "vlm":+ return _merge_credentials(old, changes, False)+ result = _merge(old, changes)+ if kind == "embedding":+ for mode in ("dense", "sparse", "hybrid"):+ if isinstance(changes.get(mode), dict):+ result[mode] = _merge_credentials(old.get(mode) or {}, changes[mode], True)+ return result+++def _atomic_write(path: Path, data: bytes, mode: int) -> None:+ fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)+ try:+ with os.fdopen(fd, "wb") as stream:+ if sys.platform == "win32":+ os.chmod(temporary, mode)+ else:+ os.fchmod(stream.fileno(), mode)+ stream.write(data)+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, path)+ if sys.platform != "win32":+ directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)+ try:+ os.fsync(directory)+ finally:+ os.close(directory)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+++def _apply_model_changes(raw: dict, settings: dict) -> None:+ if not settings or set(settings) - set(FORM_MODEL_KINDS):+ raise ValueError("Only model sections can be edited through the form")+ for kind, value in settings.items():+ if isinstance(value, dict):+ raw[kind] = _merge_model(raw.get(kind) or {}, value, kind)+ else:+ raise ValueError("Model configuration must be an object")+++@contextmanager+def _config_file_lock(path: Path):+ """Serialize Studio writes and restart recovery across processes."""+ lock_fd = os.open(path.with_name(f".{path.name}.studio.lock"), os.O_CREAT | os.O_RDWR, 0o600)+ with os.fdopen(lock_fd, "r+b") as lock:+ if sys.platform == "win32":+ import msvcrt++ msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)+ else:+ import fcntl++ fcntl.flock(lock, fcntl.LOCK_EX)+ yield+++def save_config_file(content: str, revision: str, server_overrides: dict | None = None) -> dict:+ """Save one startup-file revision; never update the running configuration."""+ path = _path()+ with _config_file_lock(path):+ data, _, _ = _read(path, server_overrides)+ if not revision or revision != _revision(data):+ raise ValueError("ov.conf changed; reload before saving")+ mode = stat.S_IMODE(path.stat().st_mode)+ if not mode & 0o222 or not os.access(path, os.W_OK):+ raise ValueError("ov.conf is read-only")+ _validate(content, server_overrides)+ if path.read_bytes() != data:+ raise ValueError("ov.conf changed; reload before saving")+ output = content.encode("utf-8")+ if output != data:+ _atomic_write(path.with_name(f"{path.name}.studio.bak"), data, 0o600)+ _atomic_write(path, output, mode)+ return {"revision": _revision(output), "restart_required": True}diff --git a/openviking/server/app.py b/openviking/server/app.pyindex 2cc56d60f..3e0186dfd 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -248,6 +248,7 @@ def create_app(config: Optional[ServerConfig] = None,service: Optional[OpenVikingService] = None,config_path: Optional[str] = None,+ server_overrides: Optional[dict] = None,) -> FastAPI:"""Create FastAPI application.@@ -255,6 +256,7 @@ def create_app(config: Server configuration. If None, loads from default location.service: Pre-initialized OpenVikingService (optional).config_path: Resolved ov.conf path used for startup configuration.+ server_overrides: CLI arguments reapplied when loading the startup file.Returns:FastAPI application instance@@ -433,6 +435,10 @@ def create_app()app.state.config = config+ app.state.server_config_overrides = server_overrides or {}+ from openviking.server.restart import RestartController++ app.state.restart_controller = RestartController()app.state.api_key_manager = Noneapp.state.deletion_service = Noneset_server_config(config)diff --git a/openviking/server/bootstrap.py b/openviking/server/bootstrap.pyindex 29e45e1bf..e0a95a9ae 100644--- a/openviking/server/bootstrap.py+++ b/openviking/server/bootstrap.py@@ -130,6 +130,19 @@ def _resolve_cli_config_for_bot(config_path: Optional[str]) -> Optional[str]:def main():+ """Run the CLI with one recovery attempt for remote restart startup failures."""+ from openviking.server.restart import RestartRecovery++ recovery = RestartRecovery()+ try:+ _main(recovery)+ except (Exception, SystemExit) as exc:+ if not isinstance(exc, SystemExit) or exc.code not in (None, 0):+ recovery.rollback()+ raise+++def _main(recovery):"""Main entry point for openviking-server command."""parser = argparse.ArgumentParser(description="OpenViking HTTP Server",@@ -276,6 +289,9 @@ def main():if args.with_bot:config.with_bot = True+ if recovery.pending and config.workers > 1:+ raise ValueError("Remote restart recovery requires a single worker")+bot_process: Optional[BotProcess] = Noneif config.with_bot:import secrets@@ -311,17 +327,23 @@ def main():)sys.exit(1)- # Create and run server app- app = create_app(- config,- config_path=(- str(resolved_config_path) if resolved_config_path is not None else args.config- ),- )- workers_info = f" (workers: {config.workers})" if config.workers > 1 else ""- print(f"OpenViking HTTP Server is running on {config.host}:{config.port}{workers_info}")-+ restart_requested = Falsetry:+ # Create and run server app+ app = create_app(+ config,+ server_overrides={+ key: getattr(config, key)+ for key in ("host", "port", "workers", "with_bot")+ if getattr(args, key) is not None and (key != "with_bot" or args.with_bot)+ },+ config_path=(+ str(resolved_config_path) if resolved_config_path is not None else args.config+ ),+ )+ workers_info = f" (workers: {config.workers})" if config.workers > 1 else ""+ print(f"OpenViking HTTP Server is running on {config.host}:{config.port}{workers_info}")+workers = config.workersif workers > 1:# Multi-worker mode requires an import string so each worker@@ -340,8 +362,9 @@ def main():log_config=None,)else:- uvicorn.run(+ restart_requested = _run_restartable_server(app,+ recovery=recovery,host=config.host,port=config.port,timeout_keep_alive=config.timeout_keep_alive,@@ -351,6 +374,33 @@ def main():# Cleanup vikingbot process on shutdownif bot_process is not None:_stop_vikingbot_gateway(bot_process)+ if restart_requested:+ # Preserve the interpreter, CLI arguments, cwd and environment. Replacing+ # this process also keeps its PID and relationship to systemd/Docker.+ if resolved_config_path is not None:+ os.environ[OPENVIKING_CONFIG_ENV] = str(resolved_config_path)+ os.execv(sys.executable, [sys.executable, *sys.orig_argv[1:]])+++def _run_restartable_server(app, recovery=None, **kwargs) -> bool:+ from openviking.server.restart import RestartController++ server = uvicorn.Server(uvicorn.Config(app, **kwargs))+ controller = RestartController(lambda: setattr(server, "should_exit", True), recovery)+ app.state.restart_controller = controller+ if recovery is not None:+ startup = server.startup++ async def startup_with_recovery(*args, **kwargs):+ await startup(*args, **kwargs)+ if server.started:+ recovery.ready()++ server.startup = startup_with_recovery+ server.run()+ if recovery is not None and recovery.pending:+ raise RuntimeError("Server failed to complete startup")+ return controller.requesteddef _handle_vikingbot_failure(output: str, returncode: int) -> None:diff --git a/openviking/server/restart.py b/openviking/server/restart.pynew file mode 100644index 000000000..a019dc279--- /dev/null+++ b/openviking/server/restart.py@@ -0,0 +1,116 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Process-local restart capability, installed by the single-worker CLI."""++import asyncio+import hashlib+import json+import os+import stat+import sys+import tempfile+from collections.abc import Callable+from pathlib import Path+from uuid import uuid4++from openviking_cli.exceptions import FailedPreconditionError++_RECOVERY_ENV = "OPENVIKING_RESTART_RECOVERY"+_ROLLED_BACK_ENV = "OPENVIKING_RESTART_ROLLED_BACK"+++class RestartRecovery:+ """Recover once from startup failures; disarm after lifespan and socket binding."""++ def __init__(self):+ self.pending = json.loads(os.environ.pop(_RECOVERY_ENV, "null"))+ self.rolled_back = os.environ.pop(_ROLLED_BACK_ENV, "") == "1"++ def prepare(self, revision: str) -> None:+ from openviking.config.config_file import _atomic_write, _config_file_lock+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton++ path = OpenVikingConfigSingleton.get_config_file()+ content = OpenVikingConfigSingleton.get_config_file_content()+ if path is None or content is None:+ raise ValueError("Startup configuration is unavailable for restart recovery")+ with _config_file_lock(path):+ if hashlib.sha256(path.read_bytes()).hexdigest() != revision:+ raise ValueError("ov.conf changed; reload before restarting")+ fd, name = tempfile.mkstemp(+ prefix=f".{path.name}.studio.restart.", suffix=".bak", dir=path.parent+ )+ os.close(fd)+ backup = Path(name)+ try:+ _atomic_write(backup, content, 0o600)+ os.environ[_RECOVERY_ENV] = json.dumps(+ {"path": str(path), "backup": str(backup), "revision": revision}+ )+ except BaseException:+ backup.unlink(missing_ok=True)+ raise++ def ready(self) -> None:+ pending, self.pending = self.pending, None+ if pending:+ try:+ Path(pending["backup"]).unlink(missing_ok=True)+ except OSError:+ print("Could not remove the private restart recovery backup", file=sys.stderr)++ def rollback(self) -> None:+ from openviking.config.config_file import _atomic_write, _config_file_lock++ pending, self.pending = (+ self.pending or json.loads(os.environ.pop(_RECOVERY_ENV, "null")),+ None,+ )+ if not pending:+ return+ path = Path(pending["path"])+ with _config_file_lock(path):+ if hashlib.sha256(path.read_bytes()).hexdigest() != pending["revision"]:+ raise RuntimeError(+ "ov.conf changed after restart; refusing to overwrite external edits"+ )+ backup = Path(pending["backup"])+ _atomic_write(path, backup.read_bytes(), stat.S_IMODE(path.stat().st_mode))+ backup.unlink()+ os.environ[_ROLLED_BACK_ENV] = "1"+ print(+ "Startup failed; restored the previous running configuration and retrying once",+ file=sys.stderr,+ )+ os.execv(sys.executable, [sys.executable, *sys.orig_argv[1:]])+++class RestartController:+ def __init__(+ self, shutdown: Callable[[], None] | None = None, recovery: RestartRecovery | None = None+ ):+ self.instance_id = uuid4().hex+ self.shutdown = shutdown+ self.requested = False+ self.lock = asyncio.Lock()+ self.recovery = recovery++ def status(self) -> dict:+ return {+ "supported": self.shutdown is not None,+ "instance_id": self.instance_id,+ "restarting": self.requested,+ "rolled_back": bool(self.recovery and self.recovery.rolled_back),+ }++ def request(self) -> dict:+ if self.shutdown is None:+ raise FailedPreconditionError(+ "Remote restart requires the single-worker openviking-server CLI"+ )+ self.requested = True+ return self.status()++ def stop(self) -> None:+ if self.requested and self.shutdown is not None:+ self.shutdown()diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 467905952..27d591bc1 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -6,7 +6,8 @@ import asynciofrom collections.abc import Mappingfrom typing import Any, Optional-from fastapi import APIRouter, Body, Depends, Path, Query, Request+from fastapi import APIRouter, BackgroundTasks, Body, Depends, Path, Query, Request+from fastapi import Response as HTTPResponsefrom pydantic import BaseModel, Fieldfrom openviking.config.scope import ConfigScope@@ -138,6 +139,8 @@ class ConfigPatchRequest(BaseModel):"""settings: dict[str, Any] = Field(default_factory=dict)+ revision: str | None = None+ content: str | None = None_ROOT_ONLY_ACCOUNT_CONFIG_SECTIONS = frozenset({"vlm", "query_planner", "embedding", "vectordb"})@@ -804,22 +807,124 @@ async def patch_account_configuration(@require_auth_rootasync def get_cluster_configuration(request: Request,+ response: HTTPResponse,+ source: str = Query("runtime", pattern="^(runtime|file)$"),+ account_id: str | None = Query(None),ctx: RequestContext = Depends(get_request_context),):"""Return the cluster layer's explicit runtime configuration."""runtime_config = _get_runtime_config_manager()+ if source == "file":+ from openviking.config.config_file import read_config_file++ response.headers["Cache-Control"] = "no-store"+ try:+ result = await asyncio.to_thread(+ read_config_file, getattr(request.app.state, "server_config_overrides", None)+ )+ except (ValueError, OSError) as exc:+ raise FailedPreconditionError(+ "Cannot read the server startup configuration file"+ ) from exc+ cluster = await runtime_config.get_settings(ConfigScope.cluster())+ account = (+ await runtime_config.get_settings(ConfigScope.account(account_id)) if account_id else {}+ )+ model_kinds = ("vlm", "embedding", "query_planner", "rerank")+ result["overrides"] = {+ "cluster": [key for key in model_kinds if (cluster or {}).get(key) is not None],+ "account": [key for key in model_kinds if (account or {}).get(key) is not None],+ }+ result["restart"] = request.app.state.restart_controller.status()+ return Response(status="ok", result=result)settings = await runtime_config.get_settings(ConfigScope.cluster())return Response(status="ok", result={"settings": settings})+class RestartRequest(BaseModel):+ revision: str = Field(min_length=1)++[email protected]("/restart", status_code=202)+@require_auth_root+async def restart_server(+ body: RestartRequest,+ request: Request,+ background_tasks: BackgroundTasks,+ response: HTTPResponse,+ ctx: RequestContext = Depends(get_request_context),+):+ from openviking.config.config_file import preview_config_file, read_config_file++ controller = request.app.state.restart_controller+ server_overrides = getattr(request.app.state, "server_config_overrides", None)+ if controller.shutdown is None:+ raise FailedPreconditionError(+ "Remote restart requires the single-worker openviking-server CLI"+ )+ async with controller.lock:+ try:+ config = await asyncio.to_thread(read_config_file, server_overrides)+ if config["revision"] != body.revision:+ raise ValueError("ov.conf changed; reload before restarting")+ await asyncio.to_thread(preview_config_file, config["content"], {}, server_overrides)+ if controller.recovery is not None and not controller.requested:+ await asyncio.to_thread(controller.recovery.prepare, body.revision)+ except ValueError as exc:+ raise InvalidArgumentError(str(exc)) from exc+ except OSError as exc:+ raise FailedPreconditionError(+ "Cannot read the server startup configuration file"+ ) from exc+ # Runs after the accepted response has been sent. Uvicorn drains active+ # requests and the CLI cleans up its managed Bot before replacing itself.+ result = controller.request()+ background_tasks.add_task(controller.stop)+ response.headers["Cache-Control"] = "no-store"+ return Response(status="ok", result=result)++@router.patch("/configuration")@require_auth_rootasync def patch_cluster_configuration(body: ConfigPatchRequest,request: Request,+ response: HTTPResponse,+ source: str = Query("runtime", pattern="^(runtime|file)$"),+ dry_run: bool = Query(False),ctx: RequestContext = Depends(get_request_context),):"""Apply a three-state PATCH to the cluster configuration layer."""+ if dry_run and (source != "file" or body.content is None):+ raise InvalidArgumentError("dry_run requires source=file and full file content")+ if source == "file":+ from openviking.config.config_file import preview_config_file, save_config_file++ server_overrides = getattr(request.app.state, "server_config_overrides", None)+ async with request.app.state.restart_controller.lock:+ if request.app.state.restart_controller.requested:+ raise FailedPreconditionError("Server restart is already in progress")+ response.headers["Cache-Control"] = "no-store"+ try:+ if dry_run:+ result = await asyncio.to_thread(+ preview_config_file, body.content, body.settings, server_overrides+ )+ else:+ if body.content is None or body.settings:+ raise ValueError("File saves require full content and no model settings")+ result = await asyncio.to_thread(+ save_config_file, body.content, body.revision or "", server_overrides+ )+ except ValueError as exc:+ raise InvalidArgumentError(str(exc)) from exc+ except OSError as exc:+ raise FailedPreconditionError(+ "Cannot write ov.conf; check file and directory permissions"+ ) from exc+ return Response(status="ok", result=result)+ if body.content is not None:+ raise InvalidArgumentError("Full file content requires source=file")runtime_config = _get_runtime_config_manager()try:await runtime_config.patch_cluster(body.settings)diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.pyindex 02a016159..d27f84285 100644--- a/openviking_cli/utils/config/open_viking_config.py+++ b/openviking_cli/utils/config/open_viking_config.py@@ -1,5 +1,6 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0+import hashlibimport jsonimport loggingimport os@@ -629,6 +630,9 @@ class OpenVikingConfigSingleton:_instance: Optional[OpenVikingConfig] = None_lock: Lock = Lock()_initializing: bool = False+ _config_file: Optional[Path] = None+ _config_file_revision: Optional[str] = None+ _config_file_content: Optional[bytes] = None@classmethoddef get_instance(cls) -> OpenVikingConfig:@@ -685,6 +689,9 @@ class OpenVikingConfigSingleton:try:if config_dict is not None:cls._instance = OpenVikingConfig.from_dict(config_dict)+ cls._config_file = None+ cls._config_file_revision = None+ cls._config_file_content = Noneelse:path = resolve_config_path(config_path, OPENVIKING_CONFIG_ENV, DEFAULT_OV_CONF)if path is not None:@@ -713,15 +720,19 @@ class OpenVikingConfigSingleton:if not config_path.exists():raise FileNotFoundError(f"Config file does not exist: {config_file}")- with open(config_path, "r", encoding="utf-8-sig") as f:- raw = f.read()+ data = config_path.read_bytes()+ raw = data.decode("utf-8-sig")# Expand $VAR and ${VAR} inside the JSON text (useful for container deployments).# Unset variables are left unchanged by expandvars().raw = os.path.expandvars(raw)config_data = json.loads(raw)- return OpenVikingConfig.from_dict(config_data)+ config = OpenVikingConfig.from_dict(config_data)+ cls._config_file = config_path.resolve()+ cls._config_file_revision = hashlib.sha256(data).hexdigest()+ cls._config_file_content = data+ return configexcept json.JSONDecodeError as e:raise ValueError(f"Config file JSON format error: {e}")except ValueError:@@ -740,6 +751,24 @@ class OpenVikingConfigSingleton:"""Reset the singleton instance (mainly for testing)."""with cls._lock:cls._instance = None+ cls._config_file = None+ cls._config_file_revision = None+ cls._config_file_content = None++ @classmethod+ def get_config_file_content(cls) -> Optional[bytes]:+ """Return the exact startup bytes for recovery, even after subsequent saves."""+ return cls._config_file_content++ @classmethod+ def get_config_file_revision(cls) -> Optional[str]:+ """Return the revision of the complete file read at startup."""+ return cls._config_file_revision++ @classmethod+ def get_config_file(cls) -> Optional[Path]:+ """Return the actual startup file, not a newly resolved default path."""+ return cls._config_file# Global convenience functiondiff --git a/tests/config/test_config_file.py b/tests/config/test_config_file.pynew file mode 100644index 000000000..1438ad04d--- /dev/null+++ b/tests/config/test_config_file.py@@ -0,0 +1,475 @@+import hashlib+import json+import os+import stat+import sys++import pytest++from openviking.config.config_file import preview_config_file, read_config_file, save_config_file+from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton+++def _save_form(settings: dict, revision: str) -> dict:+ draft = preview_config_file(read_config_file()["content"], settings)+ return save_config_file(draft["content"], revision)+++def config_file(tmp_path, monkeypatch):+ path = tmp_path / "custom.conf"+ raw = {+ "vlm": {+ "model": "gpt-4o",+ "provider": "openai",+ "api_key": "dummy-review-key",+ "temperature": 0.4,+ },+ "embedding": {+ "dense": {+ "provider": "openai",+ "model": "text-embedding-3-small",+ "dimension": 1024,+ "api_key": "dummy-review-key",+ "extra_body": {"routing": "keep"},+ }+ },+ "rerank": {"provider": "jev", "api_key": "dummy-review-key", "model": "jev-latest"},+ "storage": {"workspace": str(tmp_path / "data")},+ }+ path.write_text(json.dumps(raw))+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)+ monkeypatch.setattr(+ OpenVikingConfigSingleton,+ "_config_file_revision",+ hashlib.sha256(path.read_bytes()).hexdigest(),+ )+ from openviking.config.config_file import _validate++ monkeypatch.setattr(OpenVikingConfigSingleton, "_instance", _validate(json.dumps(raw)))+ return path, raw+++def test_stale_revision_readonly_invalid_and_non_model_writes_leave_file_unchanged(config_file):+ path, _ = config_file+ revision = read_config_file()["revision"]+ original = path.read_bytes()+ for settings, version in [+ ({"vlm": {"timeout": 30}}, "stale"),+ ({"storage": {}}, revision),+ ({"vlm": {"timeout": "invalid"}}, revision),+ ({"vlm": None}, revision),+ ]:+ with pytest.raises(ValueError):+ _save_form(settings, version)+ assert path.read_bytes() == original+ path.chmod(0o444)+ assert not read_config_file()["writable"]+ with pytest.raises(ValueError, match="read-only"):+ _save_form({"vlm": {"timeout": 30}}, revision)+ assert path.read_bytes() == original+++def test_embedding_binding_rotation_preserves_implicit_input_and_identity(config_file):+ path, raw = config_file+ result = read_config_file()+ _save_form(+ {"embedding": {"dense": {"credentials": [{"provider": "openai", "api_key": "rotated"}]}}},+ result["revision"],+ )+ dense = json.loads(path.read_text())["embedding"]["dense"]+ assert "input" not in dense+ assert dense["model"] == raw["embedding"]["dense"]["model"]+ assert dense["dimension"] == 1024 and dense["extra_body"] == {"routing": "keep"}+++def test_programmatic_configuration_never_guesses_a_file(monkeypatch):+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", None)+ with pytest.raises(ValueError, match="without a configuration file"):+ read_config_file()+++def test_embedding_credentials_display_parent_fallbacks(config_file):+ path, raw = config_file+ raw["embedding"]["dense"]["credentials"] = [{"id": "primary", "provider": "openai"}]+ path.write_text(json.dumps(raw))+ binding = read_config_file()["models"]["embedding"]["config"]["dense"]["credentials"][0]+ assert binding["model"] == "text-embedding-3-small"+ assert binding["api_key"] == "dummy-review-key"++[email protected]("kind", ["vlm", "embedding"])+def test_cleared_legacy_binding_fields_do_not_return(config_file, kind):+ path, raw = config_file+ section = raw["vlm"] if kind == "vlm" else raw["embedding"]["dense"]+ section.update(api_base="https://old.example/v1", extra_headers={"X-Old": "obsolete"})+ path.write_text(json.dumps(raw))+ result = read_config_file()+ config = result["models"][kind]["config"]+ binding_section = config if kind == "vlm" else config["dense"]+ binding_section["credentials"][0].update(api_base=None, extra_headers={})+ _save_form({kind: config}, result["revision"])+ stored = json.loads(path.read_text())+ stored_section = stored[kind] if kind == "vlm" else stored[kind]["dense"]+ assert "api_base" not in stored_section and "api_key" not in stored_section+ current = read_config_file()["models"][kind]["config"]+ current_section = current if kind == "vlm" else current["dense"]+ assert not current_section["credentials"][0].get("api_base")+ assert not current_section["credentials"][0].get("extra_headers")+ assert current_section["credentials"][0]["api_key"] == "dummy-review-key"+++def test_partial_credentials_preserve_inherited_fields(config_file):+ path, raw = config_file+ raw["vlm"].update(api_base="https://example.com/v1", extra_headers={"X-Keep": "yes"})+ path.write_text(json.dumps(raw))+ result = read_config_file()+ _save_form({"vlm": {"credentials": [{"model": "gpt-4o-mini"}]}}, result["revision"])+ current = read_config_file()["models"]["vlm"]["config"]["credentials"][0]+ assert current["api_base"] == "https://example.com/v1"+ assert current["api_key"] == "dummy-review-key"+ assert current["extra_headers"] == {"X-Keep": "yes"}+++def test_first_vlm_connection_does_not_keep_an_empty_preferred_binding(config_file):+ path, raw = config_file+ raw.pop("vlm")+ path.write_text(json.dumps(raw))+ loaded = read_config_file()+ model = loaded["models"]["vlm"]["config"]+ assert model["credentials"] == []+ model["model"] = "gpt-4o"+ model["credentials"].append(+ {"id": "first", "provider": "openai", "api_key": "test-key", "model": "gpt-4o"}+ )+ draft = preview_config_file(loaded["content"], {"vlm": model})+ save_config_file(draft["content"], loaded["revision"])+ config = OpenVikingConfigSingleton._load_from_file(str(path))+ assert len(config.vlm.credentials) == 1+ assert config.vlm.credentials[0].id == "first"+ assert config.vlm.is_available()++[email protected]("provider_name", ["openai", " OpenAI ", "OpenAI"])[email protected]("existing", [False, True])+def test_partial_credentials_use_the_effective_legacy_provider(+ config_file, provider_name, existing+):+ path, raw = config_file+ legacy = {+ "model": "gpt-4o",+ "providers": {+ provider_name: {"api_key": "dummy-review-key", "api_base": "https://example.com/v1"},+ "litellm": {"api_key": "backup-key"},+ },+ }+ if existing:+ raw["vlm"] = legacy+ else:+ raw.pop("vlm")+ path.write_text(json.dumps(raw))+ loaded = read_config_file()+ changes = {"credentials": [{"model": "gpt-4o-mini"}]}+ if not existing:+ changes = {**legacy, **changes}+ _save_form({"vlm": changes}, loaded["revision"])+ stored = json.loads(path.read_text())["vlm"]+ assert "providers" not in stored+ assert stored["credentials"][0]["api_key"] == "dummy-review-key"+ assert stored["credentials"][0]["api_base"] == "https://example.com/v1"+ config = OpenVikingConfigSingleton._load_from_file(str(path))+ assert config.vlm.is_available()+ assert config.vlm.credentials[0].provider == "openai"+ assert config.vlm.credentials[0].model == "gpt-4o-mini"+++def test_provider_switch_does_not_reuse_legacy_headers_or_endpoint(config_file):+ path, raw = config_file+ raw["vlm"].update(+ provider="volcengine",+ api_base="https://old.example/api/v3",+ extra_headers={"Authorization": "old"},+ )+ path.write_text(json.dumps(raw))+ result = read_config_file()+ config = result["models"]["vlm"]["config"]+ config["credentials"][0].update(+ provider="openai", api_key="new-key", api_base=None, extra_headers=None+ )+ _save_form({"vlm": config}, result["revision"])+ binding = read_config_file()["models"]["vlm"]["config"]["credentials"][0]+ assert binding["provider"] == "openai" and binding["api_key"] == "new-key"+ assert not binding.get("api_base") and not binding.get("extra_headers")+++def test_keyless_embedding_does_not_inherit_legacy_key(config_file):+ path, _ = config_file+ result = read_config_file()+ _save_form(+ {+ "embedding": {+ "dense": {+ "credentials": [+ {+ "provider": "openai",+ "api_key": None,+ "api_base": "http://localhost:8000/v1",+ }+ ]+ }+ }+ },+ result["revision"],+ )+ current = read_config_file()["models"]["embedding"]["config"]["dense"]["credentials"][0]+ assert not current.get("api_key")+ assert current["api_base"] == "http://localhost:8000/v1"++[email protected]("null_provider", [False, True])+def test_partial_embedding_credentials_preserve_legacy_backend(config_file, null_provider):+ path, raw = config_file+ dense = raw["embedding"]["dense"]+ dense["backend"] = dense.pop("provider")+ if null_provider:+ dense["provider"] = None+ path.write_text(json.dumps(raw))+ result = read_config_file()+ _save_form(+ {"embedding": {"dense": {"credentials": [{"api_key": "rotated"}]}}}, result["revision"]+ )+ current = read_config_file()["models"]["embedding"]["config"]["dense"]+ assert current["credentials"][0]["provider"] == "openai"+ assert current["credentials"][0]["api_key"] == "rotated"+++def test_full_file_draft_preserves_other_sections_and_does_not_publish(config_file):+ path, raw = config_file+ raw["server"] = {"port": 1933, "root_api_key": "dummy-review-key"}+ path.write_text(json.dumps(raw))+ before = path.read_bytes()+ revision = read_config_file()["revision"]+ raw["server"]["port"] = 1934+ raw["storage"]["workspace"] = "/tmp/new-workspace"+ raw["query_planner"] = {+ "provider": "openai",+ "model": "planner",+ "api_key": "dummy-review-key",+ }+ text = json.dumps(raw, indent=4) + "\n"+ preview = preview_config_file(text, {"vlm": {"timeout": 48}})+ assert path.read_bytes() == before+ draft = json.loads(preview["content"])+ assert draft["server"] == raw["server"]+ assert draft["storage"] == raw["storage"]+ assert draft["query_planner"] == raw["query_planner"]+ assert draft["vlm"]["timeout"] == 48+ save_config_file(preview["content"], revision)+ assert path.read_text() == preview["content"]+ assert path.with_name(path.name + ".studio.bak").read_bytes() == before+ assert read_config_file()["restart_required"]+ assert OpenVikingConfigSingleton.get_instance().vlm.timeout != 48+++ "content",+ [+ "{",+ "[]",+ '{"server":{"port":"invalid"}}',+ '{"server":[]}',+ '{"server":{"root_api_key":""}}',+ '{"server":{"auth_mode":"api_key"}}',+ '{"server":{"auth_mode":"dev","host":"0.0.0.0"}}',+ ],+)+def test_invalid_full_file_drafts_leave_disk_unchanged(config_file, content):+ path, _ = config_file+ before = path.read_bytes()+ revision = read_config_file()["revision"]+ with pytest.raises(ValueError):+ preview_config_file(content)+ with pytest.raises(ValueError):+ save_config_file(content, revision)+ assert path.read_bytes() == before+++def test_full_file_save_obeys_revision_readonly_and_exact_content(config_file):+ path, raw = config_file+ revision = read_config_file()["revision"]+ text = json.dumps({**raw, "server": {"port": 1934}}, indent=4) + "\n"+ with pytest.raises(ValueError, match="changed"):+ save_config_file(text, "stale")+ path.chmod(0o444)+ with pytest.raises(ValueError, match="read-only"):+ save_config_file(text, revision)+ path.chmod(0o600)+ save_config_file(text, revision)+ assert path.read_text() == text+ assert read_config_file()["restart_required"]+++def test_startup_revision_tracks_non_model_changes_and_restoration(config_file, monkeypatch):+ path, raw = config_file+ monkeypatch.setattr(OpenVikingConfigSingleton, "_instance", None)+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file_revision", None)+ OpenVikingConfigSingleton.initialize(config_path=str(path))+ initial = path.read_bytes()+ assert not read_config_file()["restart_required"]+ path.write_text(json.dumps({**raw, "server": {"port": 1934}}))+ assert read_config_file()["restart_required"]+ path.write_bytes(initial)+ assert not read_config_file()["restart_required"]++[email protected]("binding_model", [None, "explicit-model"])+def test_shared_vlm_model_changes_preserve_inheritance_and_explicit_overrides(+ config_file, binding_model+):+ path, raw = config_file+ if binding_model:+ raw["vlm"]["credentials"] = [{"provider": "openai", "model": binding_model}]+ path.write_text(json.dumps(raw))+ loaded = read_config_file()+ model = loaded["models"]["vlm"]["config"]+ model["model"] = "new-model"+ draft = preview_config_file(loaded["content"], {"vlm": model})+ save_config_file(draft["content"], loaded["revision"])+ config = OpenVikingConfigSingleton._load_from_file(str(path))+ assert config.vlm.model == "new-model"+ assert config.vlm.credentials[0].model == binding_model+ assert config.vlm.credentials[0].api_key == "dummy-review-key"+ assert json.loads(path.read_text())["embedding"] == raw["embedding"]+++ "fragment,environment",+ [+ ('"api_key": "${STUDIO_TEST_KEY}"', {"STUDIO_TEST_KEY": "secret-from-env"}),+ ('"api_key": $STUDIO_TEST_KEY', {"STUDIO_TEST_KEY": '"secret-from-env"'}),+ ('"api_key": "dummy-key", "thinking": ${STUDIO_THINKING}', {"STUDIO_THINKING": "true"}),+ (+ '"credentials": $STUDIO_CREDENTIALS',+ {"STUDIO_CREDENTIALS": '[{"provider":"openai","api_key":"secret-from-env"}]'},+ ),+ (r'"api_key": "\u0024STUDIO_TEST_KEY"', {"STUDIO_TEST_KEY": "secret-from-env"}),+ ],+)+def test_environment_files_are_form_readonly_and_saved_verbatim(+ config_file, monkeypatch, fragment, environment+):+ path, _ = config_file+ for key, value in environment.items():+ monkeypatch.setenv(key, value)+ content = '{\n "vlm": {"model": "gpt-4o", "provider": "openai", ' + fragment + "}\n}\n"+ path.write_text(content)+ loaded = read_config_file()+ assert loaded["content"] == content+ assert loaded["form_readonly"] is True+ assert loaded["models"] == {kind: {"config": {}} for kind in ("vlm", "embedding")}+ assert "secret-from-env" not in json.dumps(loaded)+ with pytest.raises(ValueError, match="requires file editing"):+ preview_config_file(content, {"vlm": {"temperature": 0.7}})+ edited = content.replace('"gpt-4o"', '"gpt-4o-mini"')+ preview = preview_config_file(edited)+ assert preview["content"] == edited and preview["form_readonly"]+ save_config_file(edited, loaded["revision"])+ assert path.read_bytes() == edited.encode()+ runtime = OpenVikingConfigSingleton._load_from_file(str(path))+ if "\\u0024" in content:+ assert runtime.vlm.credentials[0].api_key == "$STUDIO_TEST_KEY"+++def test_non_model_environment_reference_blocks_form_edits(config_file, monkeypatch):+ path, raw = config_file+ monkeypatch.setenv("STUDIO_PORT", "1933")+ content = json.dumps(raw)[:-1] + ', "server": {"port": $STUDIO_PORT}}'+ path.write_text(content)+ assert read_config_file()["form_readonly"]+ with pytest.raises(ValueError, match="requires file editing"):+ preview_config_file(content, {"vlm": {"timeout": 42}})+++def test_invalid_environment_file_cannot_replace_disk(config_file, monkeypatch):+ path, _ = config_file+ original = path.read_bytes()+ revision = read_config_file()["revision"]+ monkeypatch.setenv("STUDIO_PORT", "not-json")+ with pytest.raises(ValueError):+ save_config_file('{"server":{"port":$STUDIO_PORT}}', revision)+ assert path.read_bytes() == original+++def test_form_cannot_introduce_environment_references(config_file):+ path, _ = config_file+ with pytest.raises(ValueError, match="file editor"):+ preview_config_file(path.read_text(), {"vlm": {"api_key": "${NEW_KEY}"}})+++def test_file_mode_preserves_bom_and_formatting(config_file):+ path, raw = config_file+ content = "\ufeff" + json.dumps(raw, indent=4) + "\r\n"+ path.write_bytes(content.encode())+ loaded = read_config_file()+ assert loaded["content"] == content+ assert preview_config_file(content)["content"] == content+ save_config_file(content, loaded["revision"])+ assert path.read_bytes() == content.encode()+++def test_literal_form_save_preserves_other_sections_and_private_backup(config_file):+ path, raw = config_file+ loaded = read_config_file()+ assert loaded["writable"] and not loaded["restart_required"]+ assert not loaded["form_readonly"]+ _save_form({"vlm": {"timeout": 42}}, loaded["revision"])+ saved = json.loads(path.read_text())+ assert saved == {**raw, "vlm": {**raw["vlm"], "timeout": 42}}+ backup = path.with_name(path.name + ".studio.bak")+ assert json.loads(backup.read_text()) == raw+ if sys.platform != "win32":+ assert stat.S_IMODE(backup.stat().st_mode) == 0o600+ assert OpenVikingConfigSingleton.get_instance().vlm.timeout != 42+++def test_literal_legacy_backup_bindings_remain_distinct(config_file):+ path, raw = config_file+ raw["vlm"]["backup"] = {"provider": "openai", "model": "gpt-4o-mini", "api_key": "backup-key"}+ content = json.dumps(raw)+ model = preview_config_file(content)["models"]["vlm"]["config"]+ model["timeout"] = 42+ draft = preview_config_file(content, {"vlm": model})+ from openviking.config.config_file import _validate++ runtime = _validate(draft["content"])+ assert [binding.api_key for binding in runtime.vlm.credentials] == [+ "dummy-review-key",+ "backup-key",+ ]++[email protected]("fragment", ["%STUDIO_WINDOWS_KEY%", r"\u0025STUDIO_WINDOWS_KEY%"])+def test_windows_environment_references_remain_file_only(config_file, monkeypatch, fragment):+ import ntpath++ path, raw = config_file+ monkeypatch.setenv("STUDIO_WINDOWS_KEY", "secret-from-windows-env")+ # Exercise Windows expansion without requiring a Windows host.+ monkeypatch.setattr(os.path, "expandvars", ntpath.expandvars)+ raw["vlm"]["api_key"] = fragment+ content = json.dumps(raw).replace(r"\\u0025", r"\u0025")+ path.write_text(content)+ loaded = read_config_file()+ assert loaded["form_readonly"]+ assert loaded["models"] == {kind: {"config": {}} for kind in ("vlm", "embedding")}+ assert "secret-from-windows-env" not in json.dumps(loaded)+ with pytest.raises(ValueError, match="requires file editing"):+ preview_config_file(content, {"vlm": {"timeout": 42}})+ edited = content.replace('"gpt-4o"', '"gpt-4o-mini"')+ assert preview_config_file(edited)["content"] == edited+ save_config_file(edited, loaded["revision"])+ assert path.read_bytes() == edited.encode()+ runtime = OpenVikingConfigSingleton._load_from_file(str(path))+ assert runtime.vlm.credentials[0].api_key == (+ "%STUDIO_WINDOWS_KEY%" if "\\u0025" in content else "secret-from-windows-env"+ )diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex e38cdd64f..52b154062 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -156,6 +156,9 @@ def _build_lightweight_admin_test_app() -> FastAPI:from openviking.server.routers import admin as admin_routerapp = FastAPI()+ from openviking.server.restart import RestartController++ app.state.restart_controller = RestartController()app.state.config = ServerConfig(root_api_key=ROOT_KEY)fake_service = _FakeService()app.state.fake_service = fake_service@@ -318,6 +321,138 @@ async def template_account(lightweight_admin_client):return account_id, {"X-API-Key": response.json()["result"]["user_key"]}+async def test_studio_file_configuration_permissions_revision_and_overrides(+ lightweight_admin_client, lightweight_admin_app, template_account, tmp_path, monkeypatch,+):+ from openviking.config.scope import ConfigScope+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton++ account_id, admin_headers = template_account+ config_path = tmp_path / "ov.conf"+ config_path.write_text(json.dumps({"vlm": {"provider": "openai", "model": "gpt-4o", "api_key": "file-secret"}}))+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", config_path)+ manager = lightweight_admin_app.state.fake_service.runtime_config_manager+ await manager.patch_account(account_id, {"vlm": {"model": "override-model", "credentials": [{"provider": "openai", "api_key": "account-secret"}]}})+ url = "/api/v1/admin/configuration"+ params = {"source": "file", "account_id": account_id}+ denied = await lightweight_admin_client.get(url, params=params, headers=admin_headers)+ assert denied.status_code == 403 and "file-secret" not in denied.text+ response = await lightweight_admin_client.get(url, params=params, headers=root_headers())+ assert response.status_code == 200, response.text+ assert response.headers["cache-control"] == "no-store"+ result = response.json()["result"]+ assert result["models"]["vlm"]["config"]["model"] == "gpt-4o"+ assert result["overrides"]["account"] == ["vlm"]+ # Persisted overrides still need reporting even outside the form's scope.+ await manager._source.update(+ ConfigScope.cluster(), lambda _: {"query_planner": {"model": "planner-override"}}+ )+ override_response = await lightweight_admin_client.get(+ url, params=params, headers=root_headers()+ )+ assert override_response.json()["result"]["overrides"]["cluster"] == ["query_planner"]+ content = json.loads(result["content"])+ content["rerank"] = {+ "provider": "jev", "api_key": "jev-secret", "mode": "choice", "threshold": 0+ }+ body = {"revision": result["revision"], "content": json.dumps(content)}+ assert (await lightweight_admin_client.patch(url, params={"source": "file"}, headers=admin_headers, json=body)).status_code == 403+ saved = await lightweight_admin_client.patch(url, params={"source": "file"}, headers=root_headers(), json=body)+ assert saved.status_code == 200, saved.text+ assert saved.json()["result"]["restart_required"]+ assert json.loads(config_path.read_text())["rerank"]["provider"] == "jev"+ assert (await lightweight_admin_client.patch(url, params={"source": "file"}, headers=root_headers(), json=body)).status_code == 400+ settings = await manager.get_settings(ConfigScope.account(account_id))+ assert settings["vlm"]["model"] == "override-model"++[email protected]("cli_host", [None, "127.0.0.1"])+async def test_studio_full_configuration_preview_and_save_are_root_only(+ lightweight_admin_client,+ lightweight_admin_app,+ template_account,+ tmp_path,+ monkeypatch,+ cli_host,+):+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton++ _, admin_headers = template_account+ path = tmp_path / "startup.conf"+ server = {"port": 1933}+ if cli_host:+ server.update(host="0.0.0.0", auth_mode="trusted")+ lightweight_admin_app.state.server_config_overrides = {"host": cli_host}+ path.write_text(json.dumps({"server": server, "storage": {"workspace": "/tmp/old"}}))+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)+ before = path.read_bytes()+ url = "/api/v1/admin/configuration"+ loaded = await lightweight_admin_client.get(+ url, params={"source": "file"}, headers=root_headers()+ )+ result = loaded.json()["result"]+ assert result["content"] == before.decode()+ content = json.dumps({"server": {**server, "port": 1934}, "storage": {"workspace": "/tmp/new"}})+ preview_params = {"source": "file", "dry_run": True}+ denied = await lightweight_admin_client.patch(+ url, params=preview_params, headers=admin_headers, json={"content": content}+ )+ assert denied.status_code == 403+ preview = await lightweight_admin_client.patch(+ url, params=preview_params, headers=root_headers(), json={"content": content}+ )+ assert preview.status_code == 200, preview.text+ assert preview.headers["cache-control"] == "no-store"+ assert preview.json()["result"]["content"] == content+ assert path.read_bytes() == before+ assert not path.with_name(path.name + ".studio.bak").exists()+ for params in ({"dry_run": True}, preview_params):+ rejected = await lightweight_admin_client.patch(+ url, params=params, headers=root_headers(), json={"settings": {}}+ )+ assert rejected.status_code == 400+ rejected = await lightweight_admin_client.patch(+ url, params={"dry_run": True}, headers=root_headers(), json={"content": content}+ )+ assert rejected.status_code == 400+ assert path.read_bytes() == before+ body = {"content": content, "revision": result["revision"]}+ for extra_body in (+ {"settings": {"vlm": {"timeout": 1}}},+ {**body, "settings": {"vlm": {"timeout": 1}}},+ ):+ rejected = await lightweight_admin_client.patch(+ url, params={"source": "file"}, headers=root_headers(), json=extra_body+ )+ assert rejected.status_code == 400+ assert path.read_bytes() == before+ denied = await lightweight_admin_client.patch(+ url, params={"source": "file"}, headers=admin_headers, json=body+ )+ assert denied.status_code == 403+ saved = await lightweight_admin_client.patch(+ url, params={"source": "file"}, headers=root_headers(), json=body+ )+ assert saved.status_code == 200, saved.text+ assert saved.headers["cache-control"] == "no-store"+ assert path.read_text() == content+ assert path.with_name(path.name + ".studio.bak").read_bytes() == before+ stale = await lightweight_admin_client.patch(+ url, params={"source": "file"}, headers=root_headers(), json=body+ )+ assert stale.status_code == 400+ runtime = await lightweight_admin_client.patch(url, headers=root_headers(), json=body)+ assert runtime.status_code == 400+ invalid = await lightweight_admin_client.patch(+ url,+ params=preview_params,+ headers=root_headers(),+ json={"content": '{"server":{"port":"bad"}}'},+ )+ assert invalid.status_code == 400+ assert path.read_text() == content++@pytest.mark.parametrize("memory_type",["profile", "preferences", "entities", "events", "soul", "identity"],@@ -3377,3 +3512,138 @@ async def test_user_page_summary_respects_account_access(lightweight_admin_clienheaders={"X-API-Key": admin_key},)assert denied.status_code == 403++[email protected]("cli_host", [None, "127.0.0.1"])+async def test_server_restart_requires_root_and_valid_revision(+ lightweight_admin_client,+ lightweight_admin_app,+ template_account,+ tmp_path,+ monkeypatch,+ cli_host,+):+ import os++ from openviking.config.config_file import read_config_file+ from openviking.server.restart import RestartController, RestartRecovery+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton++ account_id, admin_headers = template_account+ user = await lightweight_admin_client.post(+ f"/api/v1/admin/accounts/{account_id}/users",+ headers=admin_headers,+ json={"user_id": "restart-test-user"},+ )+ assert user.status_code == 200+ user_headers = {"X-API-Key": user.json()["result"]["user_key"]}+ stopped = Mock()+ monkeypatch.delenv("OPENVIKING_RESTART_RECOVERY", raising=False)+ monkeypatch.delenv("OPENVIKING_RESTART_ROLLED_BACK", raising=False)+ controller = RestartController(stopped, RestartRecovery())+ lightweight_admin_app.state.restart_controller = controller+ path = tmp_path / "ov.conf"+ server = {}+ server_overrides = {}+ if cli_host:+ server = {"host": "0.0.0.0", "auth_mode": "trusted"}+ server_overrides = {"host": cli_host}+ lightweight_admin_app.state.server_config_overrides = server_overrides+ path.write_text(+ json.dumps(+ {+ "server": server,+ "vlm": {"provider": "openai", "model": "gpt-4o", "api_key": "test-key"},+ }+ )+ )+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file_content", path.read_bytes())+ revision = read_config_file(server_overrides)["revision"]+ url = "/api/v1/admin/restart"+ for headers in [admin_headers, user_headers, {}]:+ assert (+ await lightweight_admin_client.get(+ "/api/v1/admin/configuration?source=file", headers=headers+ )+ ).status_code in (401, 403)+ assert (+ await lightweight_admin_client.post(url, headers=headers, json={"revision": revision})+ ).status_code in (401, 403)+ stopped.assert_not_called()+ assert not controller.requested+ status = await lightweight_admin_client.get(+ "/api/v1/admin/configuration?source=file", headers=root_headers()+ )+ assert status.json()["result"]["restart"]["supported"]+ assert status.headers["cache-control"] == "no-store"+ stale = await lightweight_admin_client.post(+ url, headers=root_headers(), json={"revision": "stale"}+ )+ assert stale.status_code == 400+ stopped.assert_not_called()+ original = path.read_bytes()+ accepted = await lightweight_admin_client.post(+ url, headers=root_headers(), json={"revision": revision}+ )+ assert accepted.status_code == 202+ assert accepted.json()["result"]["instance_id"] == controller.instance_id+ assert accepted.json()["result"]["restarting"]+ stopped.assert_called_once()+ recovery = json.loads(os.environ["OPENVIKING_RESTART_RECOVERY"])+ assert recovery["revision"] == revision+ with open(recovery["backup"], "rb") as backup:+ assert backup.read() == original+ assert path.read_bytes() == original+ blocked = await lightweight_admin_client.patch(+ "/api/v1/admin/configuration",+ params={"source": "file"},+ headers=root_headers(),+ json={"revision": revision, "content": original.decode()},+ )+ assert blocked.status_code == 412+++ "invalid_server",+ [+ {"port": "invalid"},+ {"root_api_key": ""},+ {"auth_mode": "api_key"},+ {"auth_mode": "dev", "host": "0.0.0.0"},+ ],+)+async def test_server_restart_unsupported_or_invalid_file_does_not_stop(+ lightweight_admin_client,+ lightweight_admin_app,+ tmp_path,+ monkeypatch,+ invalid_server,+):+ import hashlib++ from openviking.server.restart import RestartController+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton++ path = tmp_path / "ov.conf"+ path.write_text("{}")+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)+ url = "/api/v1/admin/restart"+ status = await lightweight_admin_client.get(+ "/api/v1/admin/configuration?source=file", headers=root_headers()+ )+ assert not status.json()["result"]["restart"]["supported"]+ assert (+ await lightweight_admin_client.post(url, headers=root_headers(), json={"revision": "r"})+ ).status_code == 412+ stopped = Mock()+ lightweight_admin_app.state.restart_controller = RestartController(stopped)+ path.write_text(json.dumps({"server": invalid_server}))+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)+ response = await lightweight_admin_client.post(+ url,+ headers=root_headers(),+ json={"revision": hashlib.sha256(path.read_bytes()).hexdigest()},+ )+ assert response.status_code == 400+ stopped.assert_not_called()diff --git a/tests/server/test_bootstrap.py b/tests/server/test_bootstrap.pyindex 9241411ec..d60932c75 100644--- a/tests/server/test_bootstrap.py+++ b/tests/server/test_bootstrap.py@@ -58,8 +58,8 @@ def test_main_keeps_config_host_when_cli_host_is_omitted(monkeypatch):),)monkeypatch.setattr(- bootstrap.uvicorn,- "run",+ bootstrap,+ "_run_restartable_server",lambda app, host, port, log_config=None, **kwargs: captured.update({"app": app, "host": host, "port": port, "log_config": log_config, **kwargs}),@@ -112,8 +112,8 @@ def test_main_coerces_cli_host_all_to_none(monkeypatch):),)monkeypatch.setattr(- bootstrap.uvicorn,- "run",+ bootstrap,+ "_run_restartable_server",lambda app, host, port, log_config=None, **kwargs: captured.update({"app": app, "host": host, "port": port, "log_config": log_config, **kwargs}),@@ -167,7 +167,7 @@ def test_main_enables_bot_logging_when_with_bot_comes_from_config(monkeypatch):monkeypatch.setattr(bootstrap, "_start_vikingbot_gateway", _fake_start)monkeypatch.setattr(bootstrap, "_stop_vikingbot_gateway", lambda process: None)- monkeypatch.setattr(bootstrap.uvicorn, "run", lambda *args, **kwargs: None)+ monkeypatch.setattr(bootstrap, "_run_restartable_server", lambda *args, **kwargs: False)bootstrap.main()@@ -359,3 +359,157 @@ def test_configure_default_executor_keeps_python_default_when_zero(monkeypatch):)app_module._configure_default_executor(ServerConfig())+++def test_restartable_server_drains_uvicorn_before_returning(monkeypatch):+ from fastapi import FastAPI++ app = FastAPI()+ server = SimpleNamespace(should_exit=False)++ def run():+ assert app.state.restart_controller.status()["supported"]+ app.state.restart_controller.request()+ app.state.restart_controller.stop()+ assert server.should_exit++ server.run = run+ monkeypatch.setattr(bootstrap.uvicorn, "Server", lambda config: server)+ assert bootstrap._run_restartable_server(app, host="127.0.0.1", port=1933)++[email protected]("app_startup_fails", [False, True])+def test_main_restart_cleans_up_bot_and_preserves_launch_command(monkeypatch, app_startup_fails):+ import sys++ config = ServerConfig(host="127.0.0.1", port=1933, with_bot=True)+ steps = []+ monkeypatch.setattr(sys, "argv", ["openviking-server", "--with-bot", "--bot-port", "19000"])+ original_argv = [sys.executable, "/venv/bin/openviking-server", *sys.argv[1:]]+ monkeypatch.setattr(sys, "orig_argv", original_argv)+ monkeypatch.setattr(bootstrap, "load_server_config", lambda path: config)+ monkeypatch.setattr(bootstrap, "resolve_config_path", lambda *a: Path("/tmp/explicit.conf"))+ monkeypatch.setattr(+ OpenVikingConfigSingleton, "initialize", classmethod(lambda cls, **kw: None)+ )+ monkeypatch.setattr(+ "openviking_cli.utils.ollama.detect_ollama_in_config", lambda c: (False, "", 0)+ )+ monkeypatch.setattr(bootstrap, "configure_uvicorn_logging", lambda: None)+ monkeypatch.setattr(bootstrap, "create_app", lambda *a, **kw: "app")+ monkeypatch.setattr(bootstrap, "_abort_if_port_in_use", lambda *a: None)+ monkeypatch.setattr(bootstrap, "_start_vikingbot_gateway", lambda *a, **kw: "bot")+ monkeypatch.setattr(+ bootstrap, "_stop_vikingbot_gateway", lambda bot: steps.append(("stop", bot))+ )+ monkeypatch.setattr(bootstrap, "_run_restartable_server", lambda *a, **kw: True)+ monkeypatch.setattr(+ os, "execv", lambda executable, args: steps.append(("exec", executable, args))+ )+ monkeypatch.setenv("OPENVIKING_CONFIG_FILE", "/tmp/explicit.conf")+ if app_startup_fails:+ def fail_app(*args, **kwargs):+ raise RuntimeError("application initialization failed")++ monkeypatch.setattr(bootstrap, "create_app", fail_app)+ with pytest.raises(RuntimeError, match="application initialization failed"):+ bootstrap.main()+ assert steps == [("stop", "bot")]+ return+ bootstrap.main()+ assert steps == [("stop", "bot"), ("exec", sys.executable, original_argv)]+ assert os.environ["OPENVIKING_CONFIG_FILE"] == "/tmp/explicit.conf"++[email protected]("failure", ["bind", "lifespan", "bootstrap", "success", "retry_failure"])+def test_restart_recovery_through_real_exec(tmp_path, monkeypatch, failure):+ """Exercise socket/lifespan failures and a single recovery with real execv."""+ import hashlib+ import json+ import socket+ import subprocess+ import sys+ import textwrap++ from openviking.server.restart import RestartRecovery++ path = tmp_path / "ov.conf"+ original = b'{"port":0,"stage":"original"}\n'+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file_content", original)+ monkeypatch.delenv("OPENVIKING_RESTART_RECOVERY", raising=False)+ monkeypatch.delenv("OPENVIKING_RESTART_ROLLED_BACK", raising=False)+ with socket.socket() as occupied:+ occupied.bind(("127.0.0.1", 0))+ occupied.listen()+ path.write_text(json.dumps({"port": occupied.getsockname()[1], "stage": failure}))+ # A normal save backup may contain an intermediate, never-started draft.+ path.with_name("ov.conf.studio.bak").write_bytes(b'{"stage":"intermediate"}')+ RestartRecovery().prepare(hashlib.sha256(path.read_bytes()).hexdigest())+ backup = Path(json.loads(os.environ["OPENVIKING_RESTART_RECOVERY"])["backup"])+ assert backup.read_bytes() == original+ if os.name != "nt":+ assert backup.stat().st_mode & 0o777 == 0o600+ script = tmp_path / "restart_probe.py"+ script.write_text(+ textwrap.dedent("""\+ import asyncio, json, sys+ from contextlib import asynccontextmanager+ from pathlib import Path+ from fastapi import FastAPI+ import openviking.server.bootstrap as bootstrap++ def run(recovery):+ path = Path(sys.argv[1])+ config = json.loads(path.read_text())+ if config['stage'] in ('bootstrap', 'retry_failure') or (sys.argv[2] == 'retry_failure' and recovery.rolled_back):+ raise SystemExit(1)+ @asynccontextmanager+ async def lifespan(app):+ if config['stage'] == 'lifespan':+ raise RuntimeError('startup failed')+ asyncio.get_running_loop().call_later(0.2, lambda: setattr(app.state.restart_controller, 'requested', True))+ asyncio.get_running_loop().call_later(0.3, lambda: app.state.restart_controller.stop())+ yield+ app = FastAPI(lifespan=lifespan)+ bootstrap._run_restartable_server(app, recovery=recovery, host='127.0.0.1',+ port=config['port'] if config['stage'] == 'bind' else 0, log_config=None)+ print('RECOVERED' if recovery.rolled_back else 'APPLIED')+ bootstrap._main = run+ bootstrap.main()+ """)+ )+ result = subprocess.run(+ [sys.executable, str(script), str(path), failure],+ env=os.environ.copy(),+ capture_output=True,+ text=True,+ timeout=40,+ )+ if failure == "retry_failure":+ assert result.returncode != 0+ assert result.stderr.count("retrying once") == 1+ assert path.read_bytes() == original+ else:+ assert result.returncode == 0, result.stderr+ assert ("APPLIED" if failure == "success" else "RECOVERED") in result.stdout+ assert (path.read_bytes() == original) == (failure != "success")+ assert not backup.exists()+++def test_restart_recovery_does_not_overwrite_external_changes(tmp_path, monkeypatch):+ import hashlib++ from openviking.server.restart import RestartRecovery++ path = tmp_path / "ov.conf"+ path.write_bytes(b"new configuration")+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)+ monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file_content", b"startup configuration")+ monkeypatch.delenv("OPENVIKING_RESTART_RECOVERY", raising=False)+ RestartRecovery().prepare(hashlib.sha256(path.read_bytes()).hexdigest())+ recovery = RestartRecovery()+ path.write_bytes(b"external edit")+ with pytest.raises(RuntimeError, match="refusing to overwrite"):+ recovery.rollback()+ assert path.read_bytes() == b"external edit"diff --git a/web-studio/src/routes/resources/-components/code-editor.tsx b/web-studio/src/components/code-editor.tsxsimilarity index 74%rename from web-studio/src/routes/resources/-components/code-editor.tsxrename to web-studio/src/components/code-editor.tsxindex 4f78dd538..a19045dcc 100644--- a/web-studio/src/routes/resources/-components/code-editor.tsx+++ b/web-studio/src/components/code-editor.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useImperativeHandle, forwardRef } from 'react'-import { EditorState } from '@codemirror/state'+import { Compartment, EditorState } from '@codemirror/state'import {EditorView,keymap,@@ -95,6 +95,32 @@ export interface CodeEditorHandle {getContent: () => string}+function accessExtensions(readOnly: boolean) {+ return [+ EditorState.readOnly.of(readOnly),+ EditorView.editable.of(!readOnly),+ ...(readOnly+ ? [keymap.of(searchKeymap)]+ : [+ highlightActiveLineGutter(),+ highlightActiveLine(),+ foldGutter(),+ indentOnInput(),+ bracketMatching(),+ closeBrackets(),+ autocompletion(),+ highlightSelectionMatches(),+ keymap.of([+ ...closeBracketsKeymap,+ ...defaultKeymap,+ ...searchKeymap,+ ...historyKeymap,+ indentWithTab,+ ]),+ ]),+ ]+}+interface CodeEditorProps {initialContent: stringfilename: string@@ -103,6 +129,9 @@ interface CodeEditorProps {enableLanguageSupport?: booleanlineWrapping?: booleanappearance?: 'editor' | 'plain'+ language?: string+ ariaLabel?: string+ onChange?: (content: string) => void}export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(@@ -115,11 +144,22 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(enableLanguageSupport = true,lineWrapping = false,appearance = 'editor',+ language,+ ariaLabel,+ onChange,},ref,) {const containerRef = useRef<HTMLDivElement>(null)const viewRef = useRef<EditorView | null>(null)+ const onChangeRef = useRef(onChange)+ const contentRef = useRef(initialContent)+ const readOnlyRef = useRef(readOnly)+ const syncingRef = useRef(false)+ const accessRef = useRef(new Compartment())+ onChangeRef.current = onChange+ contentRef.current = initialContent+ readOnlyRef.current = readOnlyuseImperativeHandle(ref, () => ({getContent: () => viewRef.current?.state.doc.toString() ?? initialContent,@@ -135,8 +175,14 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(lineNumbers(),drawSelection(),syntaxHighlighting(defaultHighlightStyle, { fallback: true }),- EditorState.readOnly.of(readOnly),- EditorView.editable.of(!readOnly),+ history(),+ EditorView.contentAttributes.of(+ ariaLabel ? { 'aria-label': ariaLabel } : {},+ ),+ EditorView.updateListener.of((update) => {+ if (update.docChanged && !syncingRef.current)+ onChangeRef.current?.(update.state.doc.toString())+ }),EditorView.theme({'&': {height: '100%',@@ -186,29 +232,6 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(}),]- if (readOnly) {- extensions.push(keymap.of(searchKeymap))- } else {- extensions.push(- highlightActiveLineGutter(),- highlightActiveLine(),- history(),- foldGutter(),- indentOnInput(),- bracketMatching(),- closeBrackets(),- autocompletion(),- highlightSelectionMatches(),- keymap.of([- ...closeBracketsKeymap,- ...defaultKeymap,- ...searchKeymap,- ...historyKeymap,- indentWithTab,- ]),- )- }-if (lineWrapping) {extensions.push(EditorView.lineWrapping)}@@ -217,7 +240,9 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(extensions.push(syntaxHighlighting(oneDarkHighlightStyle))}- const lang = enableLanguageSupport ? detectLanguage(filename) : null+ const lang = enableLanguageSupport+ ? (language ?? detectLanguage(filename))+ : nullif (lang && languageLoaders[lang]) {try {const langSupport = await languageLoaders[lang]()@@ -229,8 +254,11 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(if (destroyed) return+ extensions.push(+ accessRef.current.of(accessExtensions(readOnlyRef.current)),+ )const state = EditorState.create({- doc: initialContent,+ doc: contentRef.current,extensions,})@@ -254,11 +282,34 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(appearance,filename,isDark,- initialContent,lineWrapping,- readOnly,+ language,+ ariaLabel,])+ useEffect(() => {+ const view = viewRef.current+ if (!view || view.state.doc.toString() === initialContent) return+ syncingRef.current = true+ try {+ view.dispatch({+ changes: {+ from: 0,+ to: view.state.doc.length,+ insert: initialContent,+ },+ })+ } finally {+ syncingRef.current = false+ }+ }, [initialContent])++ useEffect(() => {+ viewRef.current?.dispatch({+ effects: accessRef.current.reconfigure(accessExtensions(readOnly)),+ })+ }, [readOnly])+return (<divref={containerRef}diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.tsindex 663bc4609..270fa01fb 100644--- a/web-studio/src/i18n/locales/en/workspace.ts+++ b/web-studio/src/i18n/locales/en/workspace.ts@@ -782,6 +782,125 @@ const workspace = {},},settings: {+ pageTitle: 'Settings',+ tabs: { connection: 'Connection', configuration: 'Server configuration' },+ models: {+ editMode: 'Editing mode',+ formMode: 'Form editor',+ fileMode: 'File editor',+ fileContent: 'ov.conf JSON',+ validateFailed: 'Configuration validation failed.',+ validating: 'Validating...',+ fileScope:+ 'Both editors share one configuration draft. Form edits cover VLM and Embedding; the file editor covers the full configuration as standard JSON. Web Studio does not support environment variable configuration. If your configuration uses environment variables, maintain ov.conf directly on the server. Saving updates ov.conf and requires a server restart. It does not restart the service or update runtime overrides.',+ invalidJsonObject: 'Enter a valid JSON object',+ copyModelId: 'Copy model ID',+ copied: 'Model ID copied',+ copyFailed: 'Copy failed',+ hasOverrides: 'Runtime overrides present',+ more: 'More actions',+ fileLocation: 'File location',+ readOnlyStatus: 'Read-only',+ pendingRestart: 'Restart pending',+ inSync: 'Matches running settings',+ discardAll: 'Discard changes',+ saveAll: 'Save configuration',+ reloadFile: 'Reload file (discard unsaved edits first)',+ restartRequired:+ 'File settings differ from running settings. Restart the server to apply them.',+ fileReadOnly:+ 'The configuration file is read-only. Saving is unavailable.',+ overrideWarning:+ 'Runtime overrides detected; these may still take precedence after restart:',+ parameters: 'Model parameters',+ advanced: 'Advanced settings',+ environmentObject:+ 'This configuration contains environment references or escaped reference symbols. The form is read-only. Web Studio does not support environment variable configuration. If your configuration uses environment variables, maintain ov.conf directly on the server.',+ embeddingContract:+ 'Model identity, dimensions and input type are fixed at account creation.',+ fields: {+ provider: 'Provider',+ text_source: 'Embedding text source',+ dimension: 'Dimensions',+ input: 'Input type',+ query_param: 'Query task',+ document_param: 'Document task',+ version: 'Model version',+ model: 'Model ID',+ api_key: 'API Key',+ api_base: 'API URL',+ api_version: 'API version',+ ak: 'Access Key',+ sk: 'Secret Key',+ host: 'Host',+ region: 'Region',+ timeout: 'Request timeout (seconds)',+ thinking: 'Thinking',+ max_input_tokens: 'Input token limit',+ extra_headers: 'Extra headers (JSON)',+ max_retries: 'Retries',+ max_concurrent: 'Concurrency limit',+ circuit_breaker: 'Circuit breaker (JSON)',+ failback_timeout_seconds: 'Failback interval (seconds)',+ failback_request_count: 'Failback request count',+ },+ listModel: 'Model ID',+ dimension: 'Dimensions',+ dense: 'Dense',+ sparse: 'Sparse',+ hybrid: 'Hybrid',+ priority: 'Order',+ preferred: 'Preferred',+ backup: 'Backup',+ priorityHint:+ 'The first entry is preferred; later entries are failover connections. This does not indicate the connection currently in use.',+ actions: 'Actions',+ moveUp: 'Move up',+ moveDown: 'Move down',+ view: 'View model',+ edit: 'Edit model',+ addModel: 'Add model',+ serverSource: 'ov.conf',+ unsaved: 'Unsaved',+ providerDefault: 'Provider default URL',+ notSet: 'Not set',+ empty: 'No model settings',+ showKey: 'Show API key',+ hideKey: 'Hide API key',+ close: 'Close',+ dismiss: 'Cancel',+ apply: 'Confirm changes',+ confirmRemove: 'Remove this model configuration?',+ vlmType: 'VLM',+ embeddingType: 'Embedding',+ loading: 'Loading model settings...',+ rootRequired:+ 'Connect with a ROOT management credential to configure models.',+ loadFailed:+ 'Could not load model settings. Check the connection, permissions and server version.',+ retry: 'Retry',+ model: 'Default model ID',+ provider: 'Provider',+ selectProvider: 'Select a provider',+ customProvider: 'Custom (OpenAI compatible)',+ apiKey: 'API key',+ apiBase: 'API URL',+ remove: 'Remove credential',+ saving: 'Saving...',+ saved: 'Saved to ov.conf. Restart the server to apply changes.',+ saveAndRestart: 'Save and restart',+ restartService: 'Restart service',+ restarting: 'Restarting the service, waiting for the connection…',+ restarted: 'Service restarted and configuration reloaded.',+ restartRolledBack:+ 'Startup with the new configuration failed. The previous running configuration was restored and the service restarted.',+ restartFailed:+ 'Could not confirm the restart. Check the service status and current configuration. If the address, port or ROOT credential changed, update connection settings and retry.',+ restartUnsupported:+ 'This launch mode does not support remote restart. Restart through your deployment platform.',+ saveFailed:+ 'Could not save. Check the model parameters and permissions, then retry.',+ },acl: {page: {advanced: 'Advanced settings',diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.tsindex 2ee898fd1..5b1cd9508 100644--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts@@ -750,6 +750,119 @@ const workspace = {},},settings: {+ pageTitle: '设置',+ tabs: { connection: '连接设置', configuration: '服务端配置' },+ models: {+ editMode: '编辑模式',+ formMode: '表单编辑',+ fileMode: '文件编辑',+ fileContent: 'ov.conf JSON',+ validateFailed: '配置校验失败。',+ validating: '校验中...',+ fileScope:+ '两种编辑模式共享同一份配置草稿。表单编辑提供 VLM 和 Embedding 常用字段,文件编辑支持完整的普通 JSON 配置。Web Studio 不提供环境变量配置支持;依赖环境变量时,请直接在服务器上维护 ov.conf。保存后需重启服务才能生效,不会自动重启或更新运行时覆盖配置。',+ invalidJsonObject: '请输入有效的 JSON 对象',+ copyModelId: '复制模型 ID',+ copied: '模型 ID 已复制',+ copyFailed: '复制失败',+ hasOverrides: '存在运行时覆盖',+ more: '更多操作',+ fileLocation: '文件位置',+ readOnlyStatus: '只读',+ pendingRestart: '待重启',+ inSync: '与运行配置一致',+ discardAll: '撤销修改',+ saveAll: '保存配置',+ reloadFile: '重新加载文件(请先撤销未保存修改)',+ restartRequired: '文件配置与运行中的配置不同,需重启服务后生效。',+ fileReadOnly: '配置文件为只读,无法保存。',+ overrideWarning: '检测到运行时覆盖,重启后这些配置仍可能优先于文件:',+ parameters: '模型参数',+ advanced: '高级配置',+ environmentObject:+ '配置含环境变量引用或转义的引用符号,表单只读。Web Studio 不提供环境变量配置支持;依赖环境变量时,请直接在服务器上维护 ov.conf。',+ embeddingContract:+ '模型身份、向量维度与输入类型为创建时配置,不能在此修改。',+ fields: {+ provider: '服务提供商',+ text_source: '嵌入文本来源',+ dimension: '向量维度',+ input: '输入类型',+ query_param: '查询任务参数',+ document_param: '文档任务参数',+ version: '模型版本',+ model: '模型 ID',+ api_key: 'API Key',+ api_base: 'API 地址',+ api_version: 'API 版本',+ ak: 'Access Key',+ sk: 'Secret Key',+ host: 'Host',+ region: 'Region',+ timeout: '请求超时(秒)',+ thinking: '深度思考(thinking)',+ max_input_tokens: '输入 Token 上限',+ extra_headers: '额外请求头(JSON)',+ max_retries: '重试次数',+ max_concurrent: '并发上限',+ circuit_breaker: '熔断参数(JSON)',+ failback_timeout_seconds: '回切间隔(秒)',+ failback_request_count: '回切请求数',+ },+ listModel: '模型 ID',+ dimension: '向量维度',+ dense: '稠密向量',+ sparse: '稀疏向量',+ hybrid: '混合向量',+ priority: '顺序',+ preferred: '首选',+ backup: '备用',+ priorityHint:+ '按配置顺序优先使用第一条,故障时切换备用;不表示当前实际使用的连接。',+ actions: '操作',+ moveUp: '上移',+ moveDown: '下移',+ view: '查看模型',+ edit: '编辑模型',+ addModel: '添加模型',+ serverSource: 'ov.conf',+ unsaved: '未保存',+ providerDefault: '服务商默认地址',+ notSet: '未设置',+ empty: '暂无模型配置',+ showKey: '显示 API Key',+ hideKey: '隐藏 API Key',+ close: '关闭',+ dismiss: '取消',+ apply: '确认修改',+ confirmRemove: '删除此模型配置?',+ vlmType: 'VLM',+ embeddingType: 'Embedding',+ loading: '正在读取服务端配置...',+ rootRequired: '需要使用 ROOT 管理凭证连接服务才能编辑服务端配置。',+ loadFailed: '服务端配置读取失败,请检查连接、权限及服务版本。',+ retry: '重试',+ model: '默认模型 ID',+ provider: '服务提供商',+ selectProvider: '选择服务提供商',+ customProvider: '自定义(OpenAI 兼容)',+ apiKey: 'API Key',+ apiBase: 'API 地址',+ remove: '删除凭证',+ saving: '保存中...',+ saved: '已保存到 ov.conf,请重启服务使改动生效',+ saveAndRestart: '保存并重启',+ restartService: '重启服务',+ restarting: '正在重启服务,等待连接恢复…',+ restarted: '服务已重启,配置已重新加载。',+ restartRolledBack:+ '新配置启动失败,已自动恢复此前运行的配置并重新启动服务。',+ restartFailed:+ '未能确认服务重启成功,请检查服务状态和当前配置。如修改了地址、端口或 ROOT 凭证,请更新连接设置后重试。',+ restartUnsupported:+ '当前启动方式不支持页面重启,请通过部署平台重启服务。',+ saveFailed: '保存失败,请检查模型参数及权限后重试。',+ },acl: {page: {advanced: '高级设置',diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsxindex e9ab94328..b95543dd3 100644--- a/web-studio/src/routes/resources/-components/file-preview.tsx+++ b/web-studio/src/routes/resources/-components/file-preview.tsx@@ -41,12 +41,12 @@ import {} from '../-hooks/viking-fm'import { useJsonFormat } from '../-hooks/use-json-format'import type { VikingFsEntry } from '../-types/viking-fm'-import type { CodeEditorHandle } from './code-editor'+import type { CodeEditorHandle } from '#/components/code-editor'import { OkfMetadataPanel } from './okf-metadata-panel'import { YamlMetadata } from './yaml-metadata'const LazyCodeEditor = lazy(() =>- import('./code-editor').then((m) => ({ default: m.CodeEditor })),+ import('#/components/code-editor').then((m) => ({ default: m.CodeEditor })),)const LazyMermaidDiagram = lazy(() =>import('./mermaid-diagram').then((m) => ({ default: m.MermaidDiagram })),diff --git a/web-studio/src/routes/settings/-components/model-fields.tsx b/web-studio/src/routes/settings/-components/model-fields.tsxnew file mode 100644index 000000000..901df3b61--- /dev/null+++ b/web-studio/src/routes/settings/-components/model-fields.tsx@@ -0,0 +1,295 @@+import * as React from 'react'+import { EyeIcon, EyeOffIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import { Button } from '#/components/ui/button'+import { Input } from '#/components/ui/input'+import { Textarea } from '#/components/ui/textarea'+import { Switch } from '#/components/ui/switch'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '#/components/ui/select'+import { Field, FieldLabel } from '#/components/ui/field'+import { PLAIN_INPUT_PROPS } from '#/lib/form-input'+import type { ModelConfig } from '../-lib/config-file-api'++export type EditableModelKind = 'vlm' | 'embedding'++const CUSTOM_OPENAI = '__custom_openai'++export type FieldSpec = {+ key: string+ type?: 'secret' | 'number' | 'json' | 'toggle'+ options?: string[]+ required?: boolean+ min?: number+}+export const providers: Record<EditableModelKind, string[]> = {+ vlm: [+ 'volcengine',+ 'openai',+ 'azure',+ 'kimi',+ 'glm',+ 'litellm',+ 'openai-codex',+ ],+ embedding: [+ 'volcengine',+ 'openai',+ 'azure',+ 'vikingdb',+ 'jina',+ 'ollama',+ 'gemini',+ 'voyage',+ 'dashscope',+ 'minimax',+ 'cohere',+ 'litellm',+ 'local',+ ],+}+export function bindingFields(+ kind: EditableModelKind,+ provider: string,+): FieldSpec[] {+ const fields: FieldSpec[] = [+ { key: 'provider', options: providers[kind], required: true },+ ]+ fields.push({ key: 'model' })+ if (provider === 'vikingdb')+ fields.push(+ { key: 'ak', type: 'secret', required: true },+ { key: 'sk', type: 'secret', required: true },+ { key: 'host' },+ ...(kind === 'embedding' ? [{ key: 'region' }] : []),+ )+ else if (!['local', 'ollama', 'openai-codex'].includes(provider))+ fields.push({+ key: 'api_key',+ type: 'secret',+ required:+ provider !== 'litellm' &&+ !(kind === 'embedding' && provider === 'openai'),+ })+ if (provider !== 'vikingdb' && provider !== 'local')+ fields.push({+ key: 'api_base',+ required: provider === 'azure',+ })+ if (provider === 'azure') fields.push({ key: 'api_version' })+ return fields+}+function JsonField({+ value,+ onChange,+ readOnly,+ id,+ required,+}: {+ value: unknown+ onChange: (value: unknown) => void+ readOnly: boolean+ id: string+ required?: boolean+}) {+ const { t } = useTranslation('settings')+ const [text, setText] = React.useState(+ value === undefined || value === null ? '' : JSON.stringify(value, null, 2),+ )+ return (+ <Textarea+ id={id}+ readOnly={readOnly}+ required={required}+ rows={4}+ className="font-mono text-xs"+ value={text}+ onChange={(event) => {+ const input = event.currentTarget+ setText(input.value)+ try {+ const parsed = input.value.trim() ? JSON.parse(input.value) : null+ if (+ parsed !== null &&+ (typeof parsed !== 'object' || Array.isArray(parsed))+ )+ throw new Error('Expected JSON object')+ input.setCustomValidity('')+ onChange(parsed)+ } catch {+ input.setCustomValidity(t('models.invalidJsonObject'))+ }+ }}+ />+ )+}+export function ModelFields({+ fields,+ value,+ onChange,+ readOnly = false,+ prefix = 'model',+ inheritedModel,+}: {+ fields: FieldSpec[]+ value: ModelConfig+ onChange: (next: ModelConfig) => void+ readOnly?: boolean+ prefix?: string+ inheritedModel?: unknown+}) {+ const { t } = useTranslation('settings')+ const [visible, setVisible] = React.useState<Record<string, boolean>>({})+ const provider = String(value.provider || '').toLowerCase()+ const [customProvider, setCustomProvider] = React.useState(+ provider === 'openai' && Boolean(value.api_base),+ )+ const needsEmbeddingBase =+ fields.some((field) => field.key === 'provider') &&+ fields.some((field) => field.key === 'api_key' && !field.required) &&+ provider === 'openai' &&+ !value.api_key+ return (+ <>+ {fields.map((field) => {+ const id = `${prefix}-${field.key}`+ const current =+ field.key === 'provider' && typeof value.provider === 'string'+ ? provider+ : field.key === 'model'+ ? value.model || inheritedModel+ : value[field.key]+ const change = (next: unknown) =>+ onChange({ ...value, [field.key]: next })+ const label = t(`models.fields.${field.key}`)+ const isProvider = field.key === 'provider'+ const options = field.options?.map((option) => ({+ value: option,+ label: option,+ }))+ if (isProvider && options)+ options.push({+ value: CUSTOM_OPENAI,+ label: t('models.customProvider'),+ })+ return (+ <Field key={field.key} className="gap-2">+ <FieldLabel htmlFor={id} className="text-xs">+ {label}+ </FieldLabel>+ {field.options ? (+ <Select+ value={+ isProvider && customProvider+ ? CUSTOM_OPENAI+ : typeof current === 'string'+ ? current+ : null+ }+ disabled={readOnly}+ required={field.required}+ items={options}+ onValueChange={(next) => {+ if (isProvider) {+ setCustomProvider(next === CUSTOM_OPENAI)+ change(next === CUSTOM_OPENAI ? 'openai' : next)+ } else change(next)+ }}+ >+ <SelectTrigger id={id} className="h-10 w-full">+ <SelectValue placeholder={t('models.selectProvider')} />+ </SelectTrigger>+ <SelectContent align="start">+ {options?.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : field.type === 'json' ? (+ <JsonField+ value={current}+ onChange={change}+ readOnly={readOnly}+ id={id}+ />+ ) : field.type === 'toggle' ? (+ <Switch+ id={id}+ checked={current === true}+ disabled={readOnly}+ onCheckedChange={change}+ />+ ) : (+ <div className="relative min-w-0">+ <Input+ {...PLAIN_INPUT_PROPS}+ id={id}+ required={+ field.key === 'api_base' &&+ (customProvider || needsEmbeddingBase)+ ? true+ : field.required+ }+ readOnly={readOnly}+ min={field.min}+ step={field.type === 'number' ? 'any' : undefined}+ type={+ field.type === 'number'+ ? 'number'+ : field.type === 'secret' && !visible[field.key]+ ? 'password'+ : 'text'+ }+ className={field.type === 'secret' ? 'h-10 pr-11' : 'h-10'}+ value={+ typeof current === 'string' || typeof current === 'number'+ ? current+ : ''+ }+ onChange={(event) =>+ change(+ event.target.value === ''+ ? null+ : field.type === 'number'+ ? Number(event.target.value)+ : event.target.value,+ )+ }+ />+ {field.type === 'secret' && (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className="absolute top-1 right-1"+ title={t(+ visible[field.key] ? 'models.hideKey' : 'models.showKey',+ )}+ aria-label={t(+ visible[field.key] ? 'models.hideKey' : 'models.showKey',+ )}+ onClick={() =>+ setVisible({+ ...visible,+ [field.key]: !visible[field.key],+ })+ }+ >+ {visible[field.key] ? <EyeOffIcon /> : <EyeIcon />}+ </Button>+ )}+ </div>+ )}+ </Field>+ )+ })}+ </>+ )+}diff --git a/web-studio/src/routes/settings/-components/server-configuration.test.tsx b/web-studio/src/routes/settings/-components/server-configuration.test.tsxnew file mode 100644index 000000000..283bdf803--- /dev/null+++ b/web-studio/src/routes/settings/-components/server-configuration.test.tsx@@ -0,0 +1,1088 @@+// @vitest-environment jsdom+import {+ cleanup,+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@testing-library/react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { afterEach, expect, it, vi } from 'vitest'+import userEvent from '@testing-library/user-event'+import { ServerConfigurationEditor } from './server-configuration'+import { Route } from '../route'+import zh from '#/i18n/locales/zh-CN/workspace'+import en from '#/i18n/locales/en/workspace'+import type { ModelConfig } from '../-lib/config-file-api'++const state = vi.hoisted(() => ({+ role: 'root',+ get: vi.fn(),+ save: vi.fn(),+ preview: vi.fn(),+ restart: vi.fn(),+ copy: vi.fn(),+}))+vi.mock('#/components/code-editor', () => ({+ CodeEditor: ({+ initialContent,+ ariaLabel,+ readOnly,+ onChange,+ }: {+ initialContent: string+ ariaLabel: string+ readOnly: boolean+ onChange: (content: string) => void+ }) => (+ <textarea+ aria-label={ariaLabel}+ value={initialContent}+ readOnly={readOnly}+ onChange={(event) => onChange(event.target.value)}+ />+ ),+}))+vi.mock('#/lib/clipboard', () => ({ copyTextToClipboard: state.copy }))+vi.mock('../-lib/config-file-api', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ createConfigFileApi: () => ({+ get: state.get,+ save: state.save,+ preview: state.preview,+ restart: state.restart,+ }),+}))+vi.mock('#/hooks/use-app-connection', () => ({+ useAppConnection: () => ({+ connection: {+ accountId: 'default',+ userId: 'default',+ baseUrl: '',+ adminApiKey: 'root',+ apiKey: '',+ },+ saveConnection: vi.fn(),+ connectionRole: state.role,+ identityScopeKey: 'default',+ serverMode: 'api_key',+ }),+}))+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ i18n: { resolvedLanguage: 'en' },+ }),+}))+afterEach(() => {+ cleanup()+ vi.resetAllMocks()+ state.role = 'root'+})+const language = {+ model: 'default-model',+ timeout: 60,+ credentials: [+ {+ id: 'a',+ provider: 'openai',+ model: 'model-a',+ api_key: 'secret-a',+ api_base: 'https://a.example.com',+ extra_headers: { keep: 'yes' },+ max_tokens: 2048,+ extra_request_body: { keep: true },+ },+ {+ id: 'b',+ provider: 'azure',+ model: 'model-b',+ api_key: 'secret-b',+ api_base: 'https://b.example.com',+ api_version: 'v1',+ },+ ],+}+const rerank = {+ provider: 'jev',+ model: 'jev-latest',+ api_key: 'jev-secret',+ api_base: 'https://api.typesafe.ai',+ mode: 'noul',+ threshold: 0.1,+ timeout: 30,+ max_input_tokens: 0,+ extra_headers: { keep: 'yes' },+ log_payloads: false,+}+const data = {+ file_path: '/server/ov.conf',+ writable: true,+ restart_required: false,+ restart: { supported: true, instance_id: 'new', restarting: false },+ revision: 'revision',+ models: {+ vlm: { config: language },+ embedding: {+ config: {+ max_retries: 3,+ max_concurrent: 10,+ dense: {+ model: 'embedding-model',+ dimension: 1024,+ input: 'text',+ credentials: [+ {+ id: 'embed',+ provider: 'openai',+ api_key: 'embedding-key',+ api_base: 'https://e.example.com',+ },+ ],+ },+ },+ },+ },+}+const file = {+ vlm: language,+ embedding: data.models.embedding.config,+ rerank,+ server: { port: 1933, root_api_key: '${ROOT_KEY}' },+ storage: { workspace: '/server/data' },+}+const content = JSON.stringify(file, null, 2)+async function apply() {+ await act(async () => {+ fireEvent.click(screen.getByText('models.apply'))+ })+}+function mount(+ payload: typeof data & {+ overrides?: { cluster: string[]; account: string[] }+ } = data,+ withSettingsTabs = false,+) {+ state.get.mockResolvedValue({ ...structuredClone(payload), content })+ state.preview.mockImplementation(async (text: string, changes = {}) => {+ const raw = { ...JSON.parse(text), ...changes }+ return {+ content: Object.keys(changes).length+ ? JSON.stringify(raw, null, 2)+ : text,+ models: Object.fromEntries(+ Object.entries(payload.models).map(([kind, entry]) => [+ kind,+ {+ ...entry,+ config: raw[kind] ?? entry.config,+ },+ ]),+ ),+ }+ })+ state.save.mockResolvedValue({ revision: 'saved-revision' })+ state.restart.mockResolvedValue({+ supported: true,+ instance_id: 'old',+ restarting: true,+ })+ state.copy.mockResolvedValue(undefined)+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ })+ const SettingsRoute = Route.options.component!+ render(+ <QueryClientProvider client={client}>+ {withSettingsTabs ? <SettingsRoute /> : <ServerConfigurationEditor />}+ </QueryClientProvider>,+ )+ return client+}+async function menuAction(+ region: ReturnType<typeof within>,+ index: number,+ name: string,+) {+ fireEvent.click(region.getAllByRole('button', { name: 'models.more' })[index])+ await act(async () => {+ fireEvent.click(await screen.findByRole('menuitem', { name }))+ })+}+function section(name: string) {+ return within(screen.getByRole('region', { name: `models.${name}` }))+}+it('includes localized contract labels in model settings', () => {+ expect(zh.settings.models.fields.dimension).toBe('向量维度')+ expect(en.settings.models.fields.dimension).toBe('Dimensions')+})+it.each([false, true])(+ 'keeps the original revision across background refresh (applied: %s)',+ async (applied) => {+ const client = mount()+ await screen.findByText('model-a')+ fireEvent.click(+ section('vlmType').getAllByRole('button', { name: 'models.edit' })[0],+ )+ fireEvent.change(screen.getByLabelText('models.fields.model'), {+ target: { value: 'draft-model' },+ })+ if (applied) await apply()+ const refreshed = structuredClone(data)+ refreshed.revision = 'external-revision'+ refreshed.models.vlm.config.timeout = 99+ state.get.mockResolvedValue({+ ...refreshed,+ content: JSON.stringify({ ...file, vlm: refreshed.models.vlm.config }),+ })+ await client.refetchQueries({+ queryKey: ['server-configuration', 'default'],+ })+ if (!applied) await apply()+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledTimes(1))+ expect(state.save.mock.calls[0][1]).toBe('revision')+ expect(JSON.parse(state.save.mock.calls[0][0]).vlm.timeout).toBe(60)+ },+)+it('allows keyless OpenAI-compatible embedding endpoints but requires an address', async () => {+ mount()+ await screen.findByText('model-a')+ fireEvent.click(+ section('embeddingType').getByRole('button', { name: 'models.edit' }),+ )+ const key = screen.getByLabelText('models.fields.api_key')+ expect(key.hasAttribute('required')).toBe(false)+ fireEvent.change(key, { target: { value: '' } })+ const base = screen.getByLabelText('models.fields.api_base')+ expect(base.hasAttribute('required')).toBe(true)+ fireEvent.change(base, { target: { value: 'http://localhost:8000/v1' } })+ await apply()+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledTimes(1))+ expect(+ JSON.parse(state.save.mock.calls[0][0]).embedding.dense.credentials[0],+ ).toMatchObject({ api_key: null, api_base: 'http://localhost:8000/v1' })+})+it('shows file scope, restart and override warnings and blocks saves to read-only files', async () => {+ mount({+ ...structuredClone(data),+ writable: false,+ restart_required: true,+ overrides: { cluster: [], account: ['vlm'] },+ })+ await screen.findByText('/server/ov.conf')+ expect(screen.getByText('models.restartRequired')).toBeTruthy()+ expect(screen.getByText('models.fileReadOnly')).toBeTruthy()+ expect(screen.getByText(/models.overrideWarning/).textContent).toContain(+ 'default.vlm',+ )+ const vlm = section('vlmType')+ await menuAction(vlm, 0, 'models.moveDown')+ expect(+ screen+ .getByRole('button', { name: 'models.saveAll' })+ .hasAttribute('disabled'),+ ).toBe(true)+ expect(state.save).not.toHaveBeenCalled()+})+it('stages additions and confirmed deletions, cancels edits and undoes the draft', async () => {+ mount()+ await screen.findByText('model-a')+ const vlm = section('vlmType')+ fireEvent.click(vlm.getByRole('button', { name: 'models.addModel' }))+ fireEvent.change(screen.getByLabelText('models.fields.model'), {+ target: { value: 'new-model' },+ })+ fireEvent.change(screen.getByLabelText('models.fields.api_key'), {+ target: { value: 'new-key' },+ })+ await apply()+ expect(vlm.getByText('new-model')).toBeTruthy()+ expect(state.save).not.toHaveBeenCalled()+ await menuAction(vlm, 2, 'models.remove')+ fireEvent.click(+ within(screen.getByRole('dialog')).getByRole('button', {+ name: 'models.dismiss',+ }),+ )+ expect(vlm.getByText('new-model')).toBeTruthy()+ await menuAction(vlm, 2, 'models.remove')+ await act(async () => {+ fireEvent.click(+ within(screen.getByRole('dialog')).getByRole('button', {+ name: 'models.remove',+ }),+ )+ })+ expect(vlm.queryByText('new-model')).toBeNull()+ fireEvent.click(vlm.getAllByRole('button', { name: 'models.edit' })[0])+ fireEvent.change(screen.getByLabelText('models.fields.model'), {+ target: { value: 'discarded' },+ })+ fireEvent.click(screen.getByText('models.dismiss'))+ expect(vlm.queryByText('discarded')).toBeNull()+ expect(screen.queryByRole('button', { name: 'models.saveAll' })).toBeNull()+ await menuAction(vlm, 0, 'models.moveDown')+ fireEvent.click(screen.getByRole('button', { name: 'models.discardAll' }))+ expect(vlm.queryByText('models.unsaved')).toBeNull()+})+it('does not fetch any model credentials without ROOT permission', () => {+ state.role = 'admin'+ mount()+ expect(screen.getByText('models.rootRequired')).toBeTruthy()+ expect(state.get).not.toHaveBeenCalled()+})+it('shows only VLM and Embedding even when other models are configured', async () => {+ mount()+ await screen.findByText('model-a')+ expect(screen.getAllByRole('region')).toHaveLength(2)+ expect(+ screen.queryByRole('region', { name: 'models.plannerType' }),+ ).toBeNull()+ expect(screen.queryByRole('region', { name: 'models.rerankType' })).toBeNull()+ expect(screen.queryByText('jev-secret')).toBeNull()+ expect(section('embeddingType').getByText(/1024/)).toBeTruthy()+})+it('copies a model ID from its menu without touching configuration', async () => {+ mount()+ await screen.findByText('model-a')+ await menuAction(section('vlmType'), 0, 'models.copyModelId')+ expect(state.copy).toHaveBeenCalledWith('model-a')+ expect(state.save).not.toHaveBeenCalled()+ expect(screen.queryByRole('button', { name: 'models.saveAll' })).toBeNull()+})+it('adds an embedding credential without changing its model contract', async () => {+ mount()+ await screen.findByText('model-a')+ fireEvent.click(+ section('embeddingType').getByRole('button', { name: 'models.addModel' }),+ )+ fireEvent.change(screen.getByLabelText('models.fields.api_key'), {+ target: { value: 'new-embedding-key' },+ })+ await apply()+ expect(+ section('embeddingType').getAllByRole('button', { name: 'models.edit' }),+ ).toHaveLength(2)+})+it('offers the target vector group when adding to multiple embedding groups', async () => {+ const payload = structuredClone(data)+ Object.assign(payload.models.embedding.config, {+ sparse: {+ model: 'sparse-model',+ credentials: [{ provider: 'local', model: 'sparse-model' }],+ },+ })+ mount(payload)+ await screen.findByText('sparse-model')+ const embedding = section('embeddingType')+ expect(+ embedding.getAllByRole('button', { name: 'models.addModel' }),+ ).toHaveLength(1)+ await userEvent.click(+ embedding.getByRole('button', { name: 'models.addModel' }),+ )+ await userEvent.click(+ await screen.findByRole('menuitem', { name: 'models.sparse' }),+ )+ fireEvent.change(screen.getByLabelText('models.fields.api_key'), {+ target: { value: 'sparse-key' },+ })+ await apply()+ expect(+ embedding.getAllByRole('button', { name: 'models.edit' }),+ ).toHaveLength(3)+})+it.each(['vlmType', 'embeddingType'])(+ 'supports a custom OpenAI-compatible endpoint for %s',+ async (kind) => {+ mount()+ await screen.findByText('model-a')+ const index = kind === 'vlmType' ? 1 : 0+ fireEvent.click(+ section(kind).getAllByRole('button', { name: 'models.edit' })[index],+ )+ fireEvent.click(screen.getByLabelText('models.fields.provider'))+ await userEvent.click(+ await screen.findByRole('option', { name: 'models.customProvider' }),+ )+ if (kind === 'vlmType')+ await waitFor(() =>+ expect(screen.queryByLabelText('models.fields.api_version')).toBeNull(),+ )+ const base = screen.getByLabelText('models.fields.api_base')+ expect(base.hasAttribute('required')).toBe(true)+ fireEvent.change(base, {+ target: { value: 'https://gateway.example.com/v1' },+ })+ fireEvent.change(screen.getByLabelText('models.fields.api_key'), {+ target: { value: 'custom-secret' },+ })+ await apply()+ expect(+ section(kind).getByText('https://gateway.example.com/v1'),+ ).toBeTruthy()+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledTimes(1))+ const changes = JSON.parse(state.save.mock.calls[0][0])+ const credentials =+ kind === 'vlmType'+ ? changes.vlm.credentials+ : changes.embedding.dense.credentials+ expect(credentials[index]).toMatchObject({+ provider: 'openai',+ api_base: 'https://gateway.example.com/v1',+ api_key: 'custom-secret',+ })+ expect(JSON.stringify(changes)).not.toContain('__custom_openai')+ },+)+it('saves visible categories together without altering hidden model settings', async () => {+ mount()+ await screen.findByText('model-a')+ expect(+ section('vlmType').getByText('models.preferred').parentElement?.textContent,+ ).toContain('model-a')+ await menuAction(section('vlmType'), 0, 'models.moveDown')+ expect(+ section('vlmType').getByText('models.backup').parentElement?.textContent,+ ).toContain('model-a')+ fireEvent.click(+ section('embeddingType').getByRole('button', { name: 'models.parameters' }),+ )+ fireEvent.change(screen.getByLabelText('models.fields.max_retries'), {+ target: { value: '5' },+ })+ await apply()+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() =>+ expect(JSON.parse(state.save.mock.calls[0][0])).toEqual({+ ...file,+ vlm: {+ ...language,+ credentials: [language.credentials[1], language.credentials[0]],+ },+ embedding: { ...data.models.embedding.config, max_retries: 5 },+ }),+ )+ expect(state.save).toHaveBeenCalledTimes(1)+})+it('keeps readonly viewing and edit transition separate from applying and saving', async () => {+ mount()+ await screen.findByText('model-a')+ fireEvent.click(+ section('vlmType').getAllByRole('button', { name: 'models.view' })[0],+ )+ let dialog = within(screen.getByRole('dialog'))+ expect(+ dialog.getByLabelText<HTMLInputElement>('models.fields.api_key').readOnly,+ ).toBe(true)+ fireEvent.click(dialog.getByRole('button', { name: 'models.edit' }))+ dialog = within(screen.getByRole('dialog'))+ expect(+ dialog.getByLabelText<HTMLInputElement>('models.fields.api_key').readOnly,+ ).toBe(false)+ expect(screen.queryByText('models.unsaved')).toBeNull()+ expect(state.save).not.toHaveBeenCalled()+})+it.each(['vlmType', 'embeddingType'])(+ 'shows the inherited model ID in view and edit without creating an override for %s',+ async (kind) => {+ const payload = structuredClone(data)+ const config =+ kind === 'vlmType'+ ? payload.models.vlm.config+ : payload.models.embedding.config.dense+ delete (config.credentials[0] as { model?: string }).model+ mount(payload)+ await screen.findByText(config.model)+ fireEvent.click(+ section(kind).getAllByRole('button', { name: 'models.view' })[0],+ )+ let dialog = within(screen.getByRole('dialog'))+ const model = dialog.getByLabelText<HTMLInputElement>('models.fields.model')+ expect(model.value).toBe(config.model)+ expect(model.readOnly).toBe(true)+ fireEvent.click(dialog.getByRole('button', { name: 'models.edit' }))+ dialog = within(screen.getByRole('dialog'))+ expect(+ dialog.getByLabelText<HTMLInputElement>('models.fields.model').value,+ ).toBe(config.model)+ fireEvent.change(dialog.getByLabelText('models.fields.api_key'), {+ target: { value: 'rotated-key' },+ })+ await apply()+ const changes = state.preview.mock.calls[0][1]+ const binding =+ kind === 'vlmType'+ ? changes.vlm.credentials[0]+ : changes.embedding.dense.credentials[0]+ expect(binding.model).toBeUndefined()+ expect(binding.api_key).toBe('rotated-key')++ fireEvent.click(+ section(kind).getAllByRole('button', { name: 'models.edit' })[0],+ )+ fireEvent.change(screen.getByLabelText('models.fields.model'), {+ target: { value: 'explicit-model' },+ })+ await apply()+ const updated = state.preview.mock.lastCall![1]+ expect(+ (kind === 'vlmType'+ ? updated.vlm.credentials[0]+ : updated.embedding.dense.credentials[0]+ ).model,+ ).toBe('explicit-model')+ },+)+it('allows embedding policy edits without exposing identity fields', async () => {+ mount()+ await screen.findByText('model-a')+ fireEvent.click(+ section('embeddingType').getByRole('button', { name: 'models.parameters' }),+ )+ expect(+ screen.getByLabelText<HTMLInputElement>('models.fields.model').readOnly,+ ).toBe(true)+ expect(+ screen.getByLabelText<HTMLInputElement>('models.fields.dimension').readOnly,+ ).toBe(true)+ fireEvent.change(screen.getByLabelText('models.fields.max_retries'), {+ target: { value: '5' },+ })+ await apply()+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() =>+ expect(JSON.parse(state.save.mock.calls[0][0])).toEqual({+ ...file,+ embedding: {+ ...data.models.embedding.config,+ max_retries: 5,+ },+ }),+ )+})+it('retains the draft after backend validation failure', async () => {+ mount()+ state.save.mockRejectedValue(new Error('Validation failed'))+ await screen.findByText('model-a')+ await menuAction(section('vlmType'), 0, 'models.moveDown')+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await screen.findByRole('alert')+ expect(section('vlmType').getByText('models.unsaved')).toBeTruthy()+ expect(screen.getByRole('alert').textContent).toContain('Validation failed')+})++it('blocks editing through View while a save is pending and closes the stale view on success', async () => {+ mount()+ let finishSave!: (value: object) => void+ state.save.mockImplementation(+ () =>+ new Promise((resolve) => {+ finishSave = resolve+ }),+ )+ await screen.findByText('model-a')+ await menuAction(section('vlmType'), 0, 'models.moveDown')+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledTimes(1))+ fireEvent.click(+ section('vlmType').getAllByRole('button', { name: 'models.view' })[0],+ )+ const dialog = within(screen.getByRole('dialog'))+ const edit = dialog.getByRole('button', { name: 'models.edit' })+ expect(edit.hasAttribute('disabled')).toBe(true)+ fireEvent.click(edit)+ expect(+ dialog.getByLabelText<HTMLInputElement>('models.fields.api_key').readOnly,+ ).toBe(true)+ expect(state.save).toHaveBeenCalledTimes(1)+ finishSave({})+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ expect(screen.queryByRole('button', { name: 'models.saveAll' })).toBeNull()+})+it('retains server diagnostics alongside the localized load failure', async () => {+ mount()+ state.get.mockRejectedValue(new Error('Startup file unavailable'))+ await screen.findByText('model-a')+ // Trigger a public refresh to fail after the initial successful read.+ fireEvent.click(screen.getByRole('button', { name: 'models.reloadFile' }))+ expect(await screen.findByText('Startup file unavailable')).toBeTruthy()+ expect(screen.getByText('models.loadFailed')).toBeTruthy()+})+it('retains unfinished dialog JSON through a failed background refresh', async () => {+ const client = mount()+ await screen.findByText('model-a')+ fireEvent.click(+ section('embeddingType').getByRole('button', { name: 'models.parameters' }),+ )+ const input = screen.getByLabelText<HTMLTextAreaElement>(+ 'models.fields.circuit_breaker',+ )+ fireEvent.change(input, { target: { value: '{unfinished' } })+ state.get.mockRejectedValue(new Error('temporary read failure'))+ await act(async () => {+ await client.refetchQueries({+ queryKey: ['server-configuration', 'default'],+ })+ })+ expect(screen.getByRole('dialog')).toBeTruthy()+ expect(+ screen.getByLabelText<HTMLTextAreaElement>('models.fields.circuit_breaker')+ .value,+ ).toBe('{unfinished')+ state.get.mockResolvedValue({ ...structuredClone(data), content })+ await act(async () => {+ await client.refetchQueries({+ queryKey: ['server-configuration', 'default'],+ })+ })+ expect(+ screen.getByLabelText<HTMLTextAreaElement>('models.fields.circuit_breaker')+ .value,+ ).toBe('{unfinished')+})+it('uses localized validation text for invalid JSON', async () => {+ mount()+ await screen.findByText('model-a')+ fireEvent.click(+ section('embeddingType').getByRole('button', { name: 'models.edit' }),+ )+ const headers = screen.getByLabelText<HTMLTextAreaElement>(+ 'models.fields.extra_headers',+ )+ fireEvent.change(headers, { target: { value: '{invalid' } })+ expect(headers.validationMessage).toBe('models.invalidJsonObject')+ expect(headers.checkValidity()).toBe(false)+ fireEvent.change(headers, { target: { value: '{"A":"B"}' } })+ expect(headers.validationMessage).toBe('')+})++it('shares form edits and whole-file edits across modes, preserving all other sections', async () => {+ mount()+ await screen.findByText('model-a')+ const tabs = within(screen.getByRole('tablist', { name: 'models.editMode' }))+ expect(+ tabs+ .getByRole('tab', { name: 'models.formMode' })+ .getAttribute('aria-selected'),+ ).toBe('true')+ fireEvent.click(+ section('vlmType').getAllByRole('button', { name: 'models.edit' })[0],+ )+ fireEvent.change(screen.getByLabelText('models.fields.model'), {+ target: { value: 'form-draft' },+ })+ await apply()+ fireEvent.click(screen.getByRole('tab', { name: 'models.fileMode' }))+ expect(+ tabs+ .getByRole('tab', { name: 'models.fileMode' })+ .getAttribute('aria-selected'),+ ).toBe('true')+ const input =+ await screen.findByLabelText<HTMLTextAreaElement>('models.fileContent')+ const raw = JSON.parse(input.value)+ expect(raw.vlm.credentials[0].model).toBe('form-draft')+ expect(raw.storage).toEqual(file.storage)+ expect(raw.server.root_api_key).toBe('${ROOT_KEY}')+ raw.server.port = 1934+ raw.vlm.credentials[0].model = 'file-draft'+ const text = JSON.stringify(raw, null, 4)+ fireEvent.change(input, { target: { value: text } })+ await act(async () => {+ fireEvent.click(screen.getByRole('tab', { name: 'models.formMode' }))+ })+ expect(await screen.findByText('file-draft')).toBeTruthy()+ expect(+ tabs+ .getByRole('tab', { name: 'models.formMode' })+ .getAttribute('aria-selected'),+ ).toBe('true')+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledWith(text, 'revision'))+ expect(state.save).toHaveBeenCalledTimes(1)+ expect(await screen.findByText('models.restartRequired')).toBeTruthy()+})+it('blocks invalid JSON from saving or switching, then discards the same draft', async () => {+ mount()+ await screen.findByText('model-a')+ fireEvent.click(screen.getByRole('tab', { name: 'models.fileMode' }))+ const input =+ await screen.findByLabelText<HTMLTextAreaElement>('models.fileContent')+ fireEvent.change(input, { target: { value: '{broken' } })+ expect(screen.getByText('models.invalidJsonObject')).toBeTruthy()+ expect(+ screen+ .getByRole('tab', { name: 'models.formMode' })+ .getAttribute('aria-disabled'),+ ).toBe('true')+ expect(+ screen+ .getByRole('button', { name: 'models.saveAll' })+ .hasAttribute('disabled'),+ ).toBe(true)+ expect(state.save).not.toHaveBeenCalled()+ fireEvent.click(screen.getByRole('button', { name: 'models.discardAll' }))+ expect(input.value).toBe(content)+ expect(screen.queryByRole('button', { name: 'models.saveAll' })).toBeNull()+})+it('keeps full-file text and its original revision after validation and save failures', async () => {+ const client = mount()+ await screen.findByText('model-a')+ fireEvent.click(screen.getByRole('tab', { name: 'models.fileMode' }))+ const text = JSON.stringify({+ ...file,+ server: { ...file.server, port: 1934 },+ })+ fireEvent.change(screen.getByLabelText('models.fileContent'), {+ target: { value: text },+ })+ state.preview.mockRejectedValue(new Error('Invalid startup configuration'))+ await act(async () => {+ fireEvent.click(screen.getByRole('tab', { name: 'models.formMode' }))+ })+ await screen.findByText(/Invalid startup configuration/)+ expect(+ screen.getByLabelText<HTMLTextAreaElement>('models.fileContent').value,+ ).toBe(text)+ state.get.mockResolvedValue({+ ...data,+ content,+ revision: 'external-revision',+ })+ await act(async () => {+ await client.refetchQueries({+ queryKey: ['server-configuration', 'default'],+ })+ })+ state.save.mockRejectedValue(new Error('ov.conf changed'))+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledWith(text, 'revision'))+ expect(+ screen.getByLabelText<HTMLTextAreaElement>('models.fileContent').value,+ ).toBe(text)+})+it('keeps the form dialog and input when draft validation fails', async () => {+ mount()+ await screen.findByText('model-a')+ state.preview.mockRejectedValue(new Error('Invalid configuration fields'))+ fireEvent.click(+ section('vlmType').getAllByRole('button', { name: 'models.edit' })[0],+ )+ fireEvent.change(screen.getByLabelText('models.fields.model'), {+ target: { value: 'rejected-model' },+ })+ await apply()+ const dialog = within(screen.getByRole('dialog'))+ expect(await dialog.findByText(/Invalid configuration fields/)).toBeTruthy()+ expect(+ dialog.getByLabelText<HTMLInputElement>('models.fields.model').value,+ ).toBe('rejected-model')+ expect(state.save).not.toHaveBeenCalled()+})++it.each(['vlmType', 'embeddingType'])(+ 'blocks all dialog inputs during draft validation for %s',+ async (kind) => {+ mount()+ await screen.findByText('model-a')+ let finishPreview!: (value: unknown) => void+ const project = state.preview.getMockImplementation()!+ state.preview.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishPreview = resolve+ }),+ )+ fireEvent.click(+ section(kind).getAllByRole('button', {+ name: kind === 'vlmType' ? 'models.edit' : 'models.parameters',+ })[0],+ )+ const dialog = screen.getByRole('dialog')+ const field = within(dialog).getByLabelText<HTMLInputElement>(+ kind === 'vlmType'+ ? 'models.fields.model'+ : 'models.fields.max_concurrent',+ )+ fireEvent.change(field, {+ target: { value: kind === 'vlmType' ? 'submitted' : '20' },+ })+ await apply()+ await waitFor(() => expect(field.readOnly).toBe(true))+ for (const input of dialog.querySelectorAll<+ HTMLInputElement | HTMLTextAreaElement+ >('input:not([aria-hidden="true"]):not([type="hidden"]), textarea')) {+ expect(input.readOnly || input.disabled, input.outerHTML).toBe(true)+ }+ // Even synthetic change events must not overwrite the in-flight snapshot.+ fireEvent.change(field, {+ target: { value: kind === 'vlmType' ? 'lost' : '30' },+ })+ const [text, changes] = state.preview.mock.calls[0]+ await act(async () => {+ finishPreview(await project(text, changes))+ })+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledTimes(1))+ const saved = JSON.parse(state.save.mock.calls[0][0])+ if (kind === 'vlmType')+ expect(saved.vlm.credentials[0].model).toBe('submitted')+ else expect(saved.embedding.max_concurrent).toBe(20)+ },+)++it('allows unquoted environment values in file drafts without resolving them in the browser', async () => {+ mount()+ await screen.findByText('model-a')+ fireEvent.click(screen.getByRole('tab', { name: 'models.fileMode' }))+ const text = content.replace('"port": 1933', '"port": ${STUDIO_PORT}')+ fireEvent.change(screen.getByLabelText('models.fileContent'), {+ target: { value: text },+ })+ expect(screen.queryByText('models.invalidJsonObject')).toBeNull()+ expect(+ screen+ .getByRole('tab', { name: 'models.formMode' })+ .hasAttribute('disabled'),+ ).toBe(false)+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledWith(text, 'revision'))+})++it.each([false, true])(+ 'toggles the shared VLM thinking policy from %s without changing bindings',+ async (initial) => {+ const payload = structuredClone(data)+ Object.assign(payload.models.vlm.config, { thinking: initial })+ mount(payload)+ await screen.findByText('model-a')+ fireEvent.click(+ section('vlmType').getByRole('button', { name: 'models.parameters' }),+ )+ const thinking = screen.getByRole('switch', {+ name: 'models.fields.thinking',+ })+ expect(thinking.getAttribute('aria-checked')).toBe(String(initial))+ fireEvent.click(thinking)+ await apply()+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledTimes(1))+ const saved = JSON.parse(state.save.mock.calls[0][0])+ expect(saved.vlm.thinking).toBe(!initial)+ expect(saved.vlm.credentials).toEqual(language.credentials)+ expect(saved.embedding).toEqual(file.embedding)+ },+)+it('saves before requesting restart and waits for a new service instance', async () => {+ mount()+ await screen.findByText('model-a')+ await menuAction(section('vlmType'), 0, 'models.moveDown')+ let finishRestart!: (value: {+ supported: boolean+ instance_id: string+ restarting: boolean+ }) => void+ state.restart.mockImplementation(+ () =>+ new Promise((resolve) => {+ finishRestart = resolve+ }),+ )+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAndRestart' }))+ await waitFor(() =>+ expect(state.restart).toHaveBeenCalledWith('saved-revision'),+ )+ expect(state.save.mock.invocationCallOrder[0]).toBeLessThan(+ state.restart.mock.invocationCallOrder[0],+ )+ expect(screen.getByText('models.restarting')).toBeTruthy()+ expect(+ section('vlmType')+ .getByRole('button', { name: 'models.addModel' })+ .hasAttribute('disabled'),+ ).toBe(true)+ await act(async () =>+ finishRestart({ supported: true, instance_id: 'old', restarting: true }),+ )+ await waitFor(() =>+ expect(screen.queryByText('models.restarting')).toBeNull(),+ )+ expect(+ screen.queryByRole('button', { name: 'models.saveAndRestart' }),+ ).toBeNull()+})+it('reports a recovered instance as a rollback rather than applying the draft', async () => {+ mount()+ await screen.findByText('model-a')+ await menuAction(section('vlmType'), 0, 'models.moveDown')+ state.restart.mockImplementation(async () => {+ state.get.mockResolvedValue({+ ...structuredClone(data),+ restart: {+ supported: true,+ instance_id: 'recovered',+ restarting: false,+ rolled_back: true,+ },+ })+ return { supported: true, instance_id: 'old', restarting: true }+ })+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAndRestart' }))+ expect(await screen.findByText('models.restartRolledBack')).toBeTruthy()+ expect(screen.queryByText('models.restarting')).toBeNull()+ expect(+ screen.queryByRole('button', { name: 'models.restartService' }),+ ).toBeNull()+})+it('does not restart after a save failure and preserves the draft', async () => {+ mount()+ await screen.findByText('model-a')+ await menuAction(section('vlmType'), 0, 'models.moveDown')+ state.save.mockRejectedValue(new Error('revision conflict'))+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAndRestart' }))+ await screen.findByText(/revision conflict/)+ expect(state.restart).not.toHaveBeenCalled()+ expect(screen.getByRole('button', { name: 'models.discardAll' })).toBeTruthy()+})+it.each([false, true])(+ 'keeps saved state and retry revision after restart rejection (refresh fails: %s)',+ async (refreshFails) => {+ mount()+ await screen.findByText('model-a')+ await menuAction(section('vlmType'), 0, 'models.moveDown')+ const recovered = {+ ...structuredClone(data),+ content,+ revision: 'saved-revision',+ }+ if (refreshFails)+ state.get.mockRejectedValue(new Error('temporary read failure'))+ else state.get.mockResolvedValue(recovered)+ state.restart.mockRejectedValue(new Error('restart unavailable'))+ fireEvent.click(+ screen.getByRole('button', { name: 'models.saveAndRestart' }),+ )+ await screen.findByText(/models.restartFailed/)+ expect(screen.getByText(/models.restartFailed/).textContent).toContain(+ 'restart unavailable',+ )+ expect(+ screen.queryByRole('button', { name: 'models.discardAll' }),+ ).toBeNull()+ expect(+ screen+ .getByRole('button', { name: 'models.restartService' })+ .hasAttribute('disabled'),+ ).toBe(false)+ expect(state.save).toHaveBeenCalledTimes(1)+ expect(screen.getAllByText('models.saved').length).toBeGreaterThan(0)+ state.get.mockResolvedValue(recovered)+ state.restart.mockResolvedValue({+ supported: true,+ instance_id: 'old',+ restarting: true,+ })+ fireEvent.click(+ screen.getByRole('button', { name: 'models.restartService' }),+ )+ await waitFor(() => expect(state.restart).toHaveBeenCalledTimes(2))+ expect(state.restart.mock.calls[1]).toEqual(['saved-revision'])+ await waitFor(() =>+ expect(+ screen.queryByRole('button', { name: 'models.restartService' }),+ ).toBeNull(),+ )+ expect(state.save).toHaveBeenCalledTimes(1)+ },+)++it('keeps the entire environment-bound form read-only and offers verbatim file editing', async () => {+ const payload = { ...structuredClone(data), form_readonly: true }+ mount(payload)+ await screen.findAllByText('models.environmentObject')+ expect(section('vlmType').queryAllByRole('button')).toHaveLength(0)+ expect(section('embeddingType').queryAllByRole('button')).toHaveLength(0)+ fireEvent.click(screen.getByRole('tab', { name: 'models.fileMode' }))+ const text = content.replace('"port": 1933', '"port": ${STUDIO_PORT}')+ fireEvent.change(await screen.findByLabelText('models.fileContent'), {+ target: { value: text },+ })+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledWith(text, 'revision'))+})++it('retains the configuration draft when switching settings tabs', async () => {+ await act(async () => {+ mount(data, true)+ })+ fireEvent.click(+ await screen.findByRole('tab', { name: 'tabs.configuration' }),+ )+ await screen.findByText('model-a')+ fireEvent.click(screen.getByRole('tab', { name: 'models.fileMode' }))+ const text = content.replace('default-model', 'unsaved-model')+ fireEvent.change(+ await screen.findByRole<HTMLTextAreaElement>('textbox', {+ name: 'models.fileContent',+ }),+ { target: { value: text } },+ )+ fireEvent.click(screen.getByRole('tab', { name: 'tabs.connection' }))+ await waitFor(() =>+ expect(+ screen.queryByRole('textbox', { name: 'models.fileContent' }),+ ).toBeNull(),+ )+ fireEvent.click(screen.getByRole('tab', { name: 'tabs.configuration' }))+ expect(+ screen.getByRole<HTMLTextAreaElement>('textbox', {+ name: 'models.fileContent',+ }).value,+ ).toBe(text)+ fireEvent.click(screen.getByRole('button', { name: 'models.saveAll' }))+ await waitFor(() => expect(state.save).toHaveBeenCalledWith(text, 'revision'))+})++it('edits uppercase VikingDB credentials with the correct auth controls', async () => {+ const payload = structuredClone(data)+ const credential: ModelConfig =+ payload.models.embedding.config.dense.credentials[0]+ Object.assign(credential, {+ provider: 'VIKINGDB',+ ak: 'dummy-ak',+ sk: 'dummy-sk',+ region: 'cn-beijing',+ })+ delete credential.api_key+ mount(payload)+ await screen.findByText('model-a')+ fireEvent.click(+ section('embeddingType').getByRole('button', { name: 'models.edit' }),+ )+ const dialog = within(screen.getByRole('dialog'))+ expect(+ dialog.getByRole('combobox', { name: 'models.fields.provider' })+ .textContent,+ ).toContain('vikingdb')+ expect(+ dialog.getByLabelText<HTMLInputElement>('models.fields.ak').value,+ ).toBe('dummy-ak')+ expect(+ dialog.getByLabelText<HTMLInputElement>('models.fields.region').value,+ ).toBe('cn-beijing')+ expect(dialog.queryByLabelText('models.fields.api_key')).toBeNull()+ fireEvent.change(dialog.getByLabelText('models.fields.sk'), {+ target: { value: 'rotated-sk' },+ })+ await apply()+ expect(+ state.preview.mock.lastCall![1].embedding.dense.credentials[0],+ ).toMatchObject({ provider: 'VIKINGDB', sk: 'rotated-sk' })+})diff --git a/web-studio/src/routes/settings/-components/server-configuration.tsx b/web-studio/src/routes/settings/-components/server-configuration.tsxnew file mode 100644index 000000000..b1e90da1b--- /dev/null+++ b/web-studio/src/routes/settings/-components/server-configuration.tsx@@ -0,0 +1,1166 @@+import * as React from 'react'+import { toast } from 'sonner'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import {+ ArrowUpIcon,+ ArrowDownIcon,+ EyeIcon,+ PencilIcon,+ PlusIcon,+ RefreshCwIcon,+ MoreHorizontalIcon,+ FileTextIcon,+ CheckIcon,+ ClockIcon,+ LockIcon,+ AlertTriangleIcon,+ CopyIcon,+ SaveIcon,+ Settings2Icon,+ Trash2Icon,+ Undo2Icon,+} from 'lucide-react'+import { useTranslation } from 'react-i18next'+import { useAppConnection } from '#/hooks/use-app-connection'+import { createRandomUuid } from '#/lib/browser-crypto'+import { copyTextToClipboard } from '#/lib/clipboard'+import { Button } from '#/components/ui/button'+import { Tabs, TabsContent, TabsList, TabsTrigger } from '#/components/ui/tabs'+import { useTheme } from 'next-themes'+import { Badge } from '#/components/ui/badge'+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from '#/components/ui/dropdown-menu'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from '#/components/ui/dialog'+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from '#/components/ui/tooltip'+import { ModelFields, bindingFields, providers } from './model-fields'+import {+ createConfigFileApi,+ embeddingModes,+ credentials,+ object,+ isConfigFileObject,+ waitForServerRestart,+} from '../-lib/config-file-api'+import type {+ ConfigFileDraft,+ ConfigFileConfiguration,+ ModelConfig,+} from '../-lib/config-file-api'+import type { EditableModelKind, FieldSpec } from './model-fields'++const LazyCodeEditor = React.lazy(() =>+ import('#/components/code-editor').then((module) => ({+ default: module.CodeEditor,+ })),+)++const visibleModelKinds: ReadonlyArray<EditableModelKind> = ['vlm', 'embedding']++function Action({+ label,+ children,+ ...props+}: React.ComponentProps<typeof Button> & { label: string }) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={label}+ {...props}+ />+ }+ >+ {children}+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ )+}+type RowProps = {+ value: ModelConfig+ fallback: ModelConfig+ index: number+ count: number+ disabled: boolean+ onView: () => void+ onEdit: () => void+ onDelete: () => void+ onMove: (index: number) => void+}+function ModelRow({+ value,+ fallback,+ index,+ count,+ disabled,+ onView,+ onEdit,+ onDelete,+ onMove,+}: RowProps) {+ const { t } = useTranslation('settings')+ const ordered = count > 1+ const modelId = String(+ value.model || value.model_name || fallback.model || t('models.notSet'),+ )+ return (+ <div+ className={`grid min-w-0 items-start gap-2 border-b bg-background py-3 text-sm md:items-center ${ordered ? 'grid-cols-[32px_minmax(0,1fr)] md:grid-cols-[32px_minmax(0,1.4fr)_100px_minmax(0,1.4fr)_80px_104px]' : 'grid-cols-[0px_minmax(0,1fr)] gap-x-0 md:grid-cols-[minmax(0,1.4fr)_100px_minmax(0,1.4fr)_80px_104px] md:gap-x-2'}`}+ >+ <span className={ordered ? 'text-xs text-muted-foreground' : 'md:hidden'}>+ {ordered ? index + 1 : null}+ </span>+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={onView}+ className="max-w-full break-all text-left font-mono text-sm font-medium hover:underline"+ >+ {modelId}+ </button>+ <Badge+ variant={index === 0 ? 'secondary' : 'outline'}+ title={t('models.priorityHint')}+ >+ {t(index === 0 ? 'models.preferred' : 'models.backup')}+ </Badge>+ </div>+ <span className="mt-1 block text-xs text-muted-foreground md:hidden">+ {String(value.provider || '')}+ </span>+ </div>+ <span className="hidden break-all md:block">+ {String(value.provider || '')}+ </span>+ <span className="col-start-2 row-start-2 min-w-0 break-all text-xs text-muted-foreground md:col-auto md:row-auto">+ {String(value.api_base || value.host || t('models.providerDefault'))}+ </span>+ <span className="col-start-2 row-start-3 font-mono text-xs text-muted-foreground md:col-auto md:row-auto">+ {value.api_key || value.sk || value.ak+ ? '********'+ : t('models.notSet')}+ </span>+ <div className="col-start-2 row-start-4 flex justify-end [&_button]:size-10 md:col-auto md:row-auto md:[&_button]:size-8">+ <Action label={t('models.view')} onClick={onView}>+ <EyeIcon />+ </Action>+ <Action label={t('models.edit')} disabled={disabled} onClick={onEdit}>+ <PencilIcon />+ </Action>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={t('models.more')}+ disabled={disabled}+ />+ }+ >+ <MoreHorizontalIcon />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-40">+ <DropdownMenuItem+ onClick={() =>+ void copyTextToClipboard(modelId)+ .then(() => toast.success(t('models.copied')))+ .catch(() => toast.error(t('models.copyFailed')))+ }+ >+ <CopyIcon />+ {t('models.copyModelId')}+ </DropdownMenuItem>+ {count > 1 && (+ <>+ <DropdownMenuItem+ disabled={index === 0}+ onClick={() => onMove(index - 1)}+ >+ <ArrowUpIcon />+ {t('models.moveUp')}+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={index === count - 1}+ onClick={() => onMove(index + 1)}+ >+ <ArrowDownIcon />+ {t('models.moveDown')}+ </DropdownMenuItem>+ </>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ disabled={count === 1}+ onClick={onDelete}+ >+ <Trash2Icon />+ {t('models.remove')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ )+}+function ModelList({+ group,+ values,+ fallback,+ disabled,+ onOrder,+ onOpen,+ onDelete,+}: {+ group: string+ values: ModelConfig[]+ fallback: ModelConfig+ disabled: boolean+ onOrder: (values: ModelConfig[]) => void+ onOpen: (index: number, readonly: boolean) => void+ onDelete: (index: number) => void+}) {+ const { t } = useTranslation('settings')+ const ids = values.map((value, index) => `${group}-${value.id || index}`)+ function move(from: number, to: number) {+ if (from < 0 || to < 0 || to >= values.length || from === to) return+ const reordered = [...values]+ const [moved] = reordered.splice(from, 1)+ reordered.splice(to, 0, moved)+ onOrder(reordered)+ }+ if (!values.length)+ return (+ <p className="py-4 text-sm text-muted-foreground">{t('models.empty')}</p>+ )+ return (+ <div className="min-w-0">+ <div+ className={`hidden gap-2 border-b pb-2 text-xs text-muted-foreground md:grid ${values.length > 1 ? 'grid-cols-[32px_minmax(0,1.4fr)_100px_minmax(0,1.4fr)_80px_104px]' : 'grid-cols-[minmax(0,1.4fr)_100px_minmax(0,1.4fr)_80px_104px]'}`}+ >+ {values.length > 1 && <span>{t('models.priority')}</span>}+ <span>{t('models.listModel')}</span>+ <span>{t('models.provider')}</span>+ <span>{t('models.apiBase')}</span>+ <span>{t('models.apiKey')}</span>+ <span className="text-right">{t('models.actions')}</span>+ </div>+ {values.map((value, index) => (+ <ModelRow+ key={ids[index]}+ value={value}+ fallback={fallback}+ index={index}+ count={values.length}+ disabled={disabled}+ onView={() => onOpen(index, true)}+ onEdit={() => onOpen(index, false)}+ onDelete={() => onDelete(index)}+ onMove={(to) => move(index, to)}+ />+ ))}+ </div>+ )+}+type Editor = {+ kind: EditableModelKind+ mode?: string+ index?: number+ value: ModelConfig+ readonly: boolean+ settings: boolean+}+const titles: Record<EditableModelKind, string> = {+ vlm: 'models.vlmType',+ embedding: 'models.embeddingType',+}+const policies: FieldSpec[] = [+ { key: 'max_retries', type: 'number', min: 0 },+ { key: 'max_concurrent', type: 'number', min: 1 },+ { key: 'circuit_breaker', type: 'json' },+]++export function ServerConfigurationEditor() {+ const { t } = useTranslation('settings')+ const { resolvedTheme } = useTheme()+ const {+ connection,+ connectionRole,+ serverMode,+ identityScopeKey,+ isConnectionRoleLoading,+ } = useAppConnection()+ const allowed =+ connectionRole === 'root' &&+ (serverMode === 'api_key' || serverMode === 'trusted')+ const api = React.useMemo(+ () => createConfigFileApi(connection, serverMode === 'trusted'),+ [connection, serverMode],+ )+ const queryClient = useQueryClient()+ const queryKey = ['server-configuration', identityScopeKey]+ const query = useQuery({+ queryKey,+ queryFn: () => api.get(),+ enabled: allowed,+ retry: false,+ })+ const [draft, setDraft] = React.useState<ConfigFileDraft | null>(null)+ const [editMode, setEditMode] = React.useState<'form' | 'file'>('form')+ const [baseline, setBaseline] =+ React.useState<ConfigFileConfiguration | null>(null)+ const [editor, setEditor] = React.useState<Editor | null>(null)+ const [confirm, setConfirm] = React.useState<{+ kind: EditableModelKind+ mode?: string+ index: number+ } | null>(null)+ const [saved, setSaved] = React.useState(false)+ const restartAbort = React.useRef<AbortController | null>(null)+ React.useEffect(() => () => restartAbort.current?.abort(), [api])+ const restartMutation = useMutation({+ mutationFn: async (revision: string) => {+ const controller = new AbortController()+ restartAbort.current = controller+ const accepted = await api.restart(revision)+ return waitForServerRestart(+ () => api.get(3000),+ accepted.instance_id,+ controller.signal,+ )+ },+ onSuccess: (result) => {+ queryClient.setQueryData(queryKey, result)+ setSaved(false)+ if (result.restart?.rolled_back)+ toast.error(t('models.restartRolledBack'))+ else toast.success(t('models.restarted'))+ },+ })+ const mutation = useMutation({+ mutationFn: ({ content }: { content: string; restart?: boolean }) =>+ api.save(content, (baseline ?? query.data)!.revision),+ onSuccess: async (result, variables) => {+ queryClient.setQueryData<ConfigFileConfiguration>(queryKey, (previous) =>+ previous+ ? {+ ...previous,+ ...result,+ content: variables.content,+ models: document?.models ?? previous.models,+ }+ : previous,+ )+ await queryClient.invalidateQueries({ queryKey })+ setDraft(null)+ setEditor(null)+ setBaseline(null)+ setSaved(true)+ toast.success(t('models.saved'))+ if (variables.restart) restartMutation.mutate(result.revision)+ },+ })+ const document = draft ?? baseline ?? query.data+ const dirty =+ draft !== null && draft.content !== (baseline ?? query.data)?.content+ const preview = useMutation({+ mutationFn: ({+ content,+ changes,+ }: {+ content: string+ changes?: Partial<Record<EditableModelKind, ModelConfig>>+ returnToForm?: boolean+ }) => api.preview(content, changes),+ onSuccess: (result, variables) => {+ setDraft(result)+ setEditor(null)+ setConfirm(null)+ if (variables.returnToForm) setEditMode('form')+ },+ })+ const pending =+ mutation.isPending || preview.isPending || restartMutation.isPending+ const invalidJson = !isConfigFileObject(document?.content ?? '{}')+ function current(kind: EditableModelKind): ModelConfig {+ return document?.models[kind].config ?? {}+ }+ function change(kind: EditableModelKind, value: ModelConfig) {+ if (pending || !document) return+ setBaseline((previous) => previous ?? query.data ?? null)+ mutation.reset()+ setSaved(false)+ preview.mutate({ content: document.content, changes: { [kind]: value } })+ }+ function bindings(kind: EditableModelKind, mode?: string) {+ const config = current(kind)+ return credentials(mode ? object(config[mode]) : config)+ }+ function reorder(+ kind: EditableModelKind,+ mode: string | undefined,+ values: ModelConfig[],+ ) {+ const config = current(kind)+ change(+ kind,+ mode+ ? {+ ...config,+ [mode]: { ...object(config[mode]), credentials: values },+ }+ : { ...config, credentials: values },+ )+ }+ function open(+ kind: EditableModelKind,+ mode?: string,+ index?: number,+ readonly = false,+ settings = false,+ ) {+ if (pending && !readonly) return+ setBaseline((previous) => previous ?? query.data ?? null)+ const config = current(kind)+ const value = settings+ ? config+ : index === undefined+ ? {+ provider: providers[kind][0],+ id: createRandomUuid(),+ }+ : bindings(kind, mode)[index]+ setEditor({+ kind,+ mode,+ index,+ readonly,+ settings,+ value: structuredClone(value),+ })+ }+ function dismissEditor() {+ setEditor(null)+ if (!dirty) {+ setDraft(null)+ setBaseline(null)+ }+ }+ function applyEditor() {+ if (!editor || editor.readonly || pending) return+ const { kind, mode, index, value, settings } = editor+ if (settings) change(kind, value)+ else {+ const values = [...bindings(kind, mode)]+ const next = Object.fromEntries(+ Object.entries(value).map(([key, item]) => [+ key,+ item === '' ? null : item,+ ]),+ )+ if (index === undefined) values.push(next)+ else values[index] = next+ const config = current(kind)+ if (!mode && !config.model)+ change(kind, {+ ...config,+ model: String(next.model || ''),+ credentials: values,+ })+ else reorder(kind, mode, values)+ }+ }+ function dismissConfirmation() {+ if (pending) return+ setConfirm(null)+ if (!dirty) {+ setDraft(null)+ setBaseline(null)+ }+ }+ function confirmAction() {+ if (!confirm || pending) return+ reorder(+ confirm.kind,+ confirm.mode,+ bindings(confirm.kind, confirm.mode).filter(+ (_, index) => index !== confirm.index,+ ),+ )+ }+ if (isConnectionRoleLoading || (allowed && query.isPending))+ return <p role="status">{t('models.loading')}</p>+ if (!allowed)+ return (+ <p role="status" className="text-muted-foreground">+ {t('models.rootRequired')}+ </p>+ )+ const loadError = query.isError ? (+ <div role="alert" className="grid gap-3">+ <p>{t('models.loadFailed')}</p>+ {query.error instanceof Error && (+ <p className="break-all text-sm text-muted-foreground">+ {query.error.message}+ </p>+ )}+ <Button+ variant="outline"+ disabled={pending}+ onClick={() => void query.refetch()}+ >+ {t('models.retry')}+ </Button>+ </div>+ ) : null+ if (query.isError && !query.data) return loadError+ const hasOverrides = Boolean(+ query.data?.overrides?.cluster.length ||+ query.data?.overrides?.account.length,+ )+ const provider = String(editor?.value.provider || '').toLowerCase()+ const fields = editor?.settings+ ? editor.kind === 'embedding'+ ? policies+ : ([+ { key: 'model', required: true },+ { key: 'timeout', type: 'number', min: 0.001 },+ { key: 'thinking', type: 'toggle' },+ ] as FieldSpec[])+ : editor+ ? bindingFields(editor.kind, provider).map((field) =>+ field.key === 'model' &&+ editor.kind === 'vlm' &&+ !current(editor.kind).model+ ? { ...field, required: true }+ : field,+ )+ : []+ return (+ <TooltipProvider>+ <div className="grid min-w-0 gap-8">+ <div className="grid gap-3 border-b pb-5 text-sm">+ {loadError}+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex flex-wrap items-center gap-3">+ <FileTextIcon className="size-4 text-muted-foreground" />+ <span className="font-medium">{t('models.serverSource')}</span>+ <Badge+ variant="outline"+ className={+ query.data?.restart_required || saved || hasOverrides+ ? 'border-amber-500/40 text-amber-700 dark:text-amber-300'+ : ''+ }+ >+ {query.data?.writable === false ? (+ <LockIcon />+ ) : hasOverrides ? (+ <AlertTriangleIcon />+ ) : query.data?.restart_required || saved ? (+ <ClockIcon />+ ) : (+ <CheckIcon />+ )}+ {t(+ query.data?.writable === false+ ? 'models.readOnlyStatus'+ : hasOverrides+ ? 'models.hasOverrides'+ : query.data?.restart_required || saved+ ? 'models.pendingRestart'+ : 'models.inSync',+ )}+ </Badge>+ </div>+ <Action+ label={t('models.reloadFile')}+ disabled={pending || query.isFetching || dirty}+ onClick={() => {+ setSaved(false)+ mutation.reset()+ preview.reset()+ setDraft(null)+ setBaseline(null)+ void query.refetch()+ }}+ >+ <RefreshCwIcon />+ </Action>+ </div>+ <details className="text-xs text-muted-foreground">+ <summary className="w-fit cursor-pointer hover:text-foreground">+ {t('models.fileLocation')}+ </summary>+ <p className="mt-2 break-all font-mono">{query.data?.file_path}</p>+ </details>+ {(query.data?.restart_required || saved) && (+ <p role="status" className="text-amber-700 dark:text-amber-300">+ {t('models.restartRequired')}+ </p>+ )}+ {restartMutation.isPending && (+ <p role="status">{t('models.restarting')}</p>+ )}+ {restartMutation.isError && (+ <p role="alert" className="text-destructive">+ {t('models.restartFailed')}{' '}+ {restartMutation.error instanceof Error+ ? restartMutation.error.message+ : ''}+ </p>+ )}+ {query.data?.restart?.rolled_back && (+ <p role="alert" className="text-destructive">+ {t('models.restartRolledBack')}+ </p>+ )}+ {query.data?.restart?.supported === false && (+ <p className="text-sm text-muted-foreground">+ {t('models.restartUnsupported')}+ </p>+ )}+ {(query.data?.restart_required || saved) &&+ query.data?.restart?.supported &&+ !dirty && (+ <Button+ type="button"+ variant="outline"+ disabled={pending}+ onClick={() => restartMutation.mutate(query.data.revision)}+ >+ {t('models.restartService')}+ </Button>+ )}+ {query.data?.writable === false && (+ <p role="alert">{t('models.fileReadOnly')}</p>+ )}+ {saved && (+ <p role="status" className="text-muted-foreground">+ {t('models.saved')}+ </p>+ )}+ {mutation.isError && (+ <p role="alert" className="text-destructive">+ {t('models.saveFailed')}{' '}+ {mutation.error instanceof Error ? mutation.error.message : ''}+ </p>+ )}+ {Boolean(+ query.data?.overrides?.cluster.length ||+ query.data?.overrides?.account.length,+ ) && (+ <p role="alert" className="text-destructive">+ {t('models.overrideWarning')}{' '}+ {[+ ...(query.data?.overrides?.cluster || []).map(+ (key) => `cluster.${key}`,+ ),+ ...(query.data?.overrides?.account || []).map(+ (key) => `${connection.accountId}.${key}`,+ ),+ ].join(', ')}+ </p>+ )}+ </div>+ <Tabs+ value={editMode}+ className="min-w-0 gap-6"+ onValueChange={(value) => {+ if (pending || value === editMode) return+ if (value === 'file') setEditMode('file')+ else if (value === 'form' && document && !invalidJson) {+ setBaseline((previous) => previous ?? query.data ?? null)+ preview.mutate({ content: document.content, returnToForm: true })+ }+ }}+ >+ <TabsList variant="line" aria-label={t('models.editMode')}>+ <TabsTrigger value="form" disabled={pending || invalidJson}>+ {t('models.formMode')}+ </TabsTrigger>+ <TabsTrigger value="file" disabled={pending}>+ {t('models.fileMode')}+ </TabsTrigger>+ </TabsList>+ <p className="text-sm text-muted-foreground">+ {t('models.fileScope')}+ </p>+ {preview.isError && !editor && !confirm && (+ <p role="alert" className="break-all text-destructive">+ {t('models.validateFailed')} {preview.error.message}+ </p>+ )}+ <TabsContent value="file" className="min-w-0">+ <div className="grid gap-3">+ <p className="text-sm font-medium">{t('models.fileContent')}</p>+ <div className="h-[min(60vh,36rem)] min-h-80 min-w-0">+ <React.Suspense+ fallback={<p role="status">{t('models.loading')}</p>}+ >+ <LazyCodeEditor+ filename="ov.conf"+ language="json"+ ariaLabel={t('models.fileContent')}+ initialContent={document?.content ?? ''}+ isDark={resolvedTheme === 'dark'}+ lineWrapping+ readOnly={pending || query.data?.writable === false}+ onChange={(content) => {+ if (pending || !document) return+ setBaseline((previous) => previous ?? query.data ?? null)+ setSaved(false)+ mutation.reset()+ preview.reset()+ setDraft({ ...document, content })+ }}+ />+ </React.Suspense>+ </div>+ {invalidJson && (+ <p role="alert" className="text-destructive">+ {t('models.invalidJsonObject')}+ </p>+ )}+ </div>+ </TabsContent>+ <TabsContent value="form" className="grid min-w-0 gap-8">+ {visibleModelKinds.map((kind) => {+ if (document?.form_readonly)+ return (+ <section key={kind} aria-label={t(titles[kind])}>+ <h2 className="mb-4 text-base font-semibold">+ {t(titles[kind])}+ </h2>+ <p className="text-sm text-muted-foreground">+ {t('models.environmentObject')}+ </p>+ </section>+ )+ const config = current(kind)+ const groups =+ kind === 'embedding'+ ? embeddingModes+ .filter((mode) => config[mode])+ .map((mode) => ({ mode, config: object(config[mode]) }))+ : [{ mode: undefined, config }]+ return (+ <section+ key={kind}+ aria-label={t(titles[kind])}+ className="min-w-0 border-b pb-6 last:border-b-0"+ >+ <div className="mb-4 flex flex-wrap items-center justify-between gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="text-base font-semibold">+ {t(titles[kind])}+ </h2>+ {dirty && (+ <Badge variant="secondary">{t('models.unsaved')}</Badge>+ )}+ </div>+ <div className="flex items-center gap-1">+ <Action+ label={t('models.parameters')}+ disabled={pending}+ onClick={() =>+ open(kind, undefined, undefined, false, true)+ }+ >+ <Settings2Icon />+ </Action>+ {kind === 'embedding' && groups.length > 1 ? (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={t('models.addModel')}+ title={t('models.addModel')}+ disabled={pending}+ />+ }+ >+ <PlusIcon />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {groups.map((group) => (+ <DropdownMenuItem+ key={group.mode}+ onClick={() => open(kind, group.mode)}+ >+ {t(`models.${group.mode}`)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <Action+ label={t('models.addModel')}+ disabled={+ pending || (kind === 'embedding' && !groups.length)+ }+ onClick={() =>+ open(+ kind,+ kind === 'embedding'+ ? groups[0]?.mode+ : undefined,+ )+ }+ >+ <PlusIcon />+ </Action>+ )}+ </div>+ </div>+ {groups.map((group) => (+ <div key={group.mode || kind} className="min-w-0">+ {group.mode && (+ <div className="mb-3 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">+ <Badge variant="outline">+ {t(`models.${group.mode}`)}+ </Badge>+ <span>+ {t('models.dimension')}:{' '}+ {String(group.config.dimension)}+ </span>+ {credentials(group.config).some(+ (binding) =>+ binding.model &&+ binding.model !== group.config.model,+ ) && (+ <span className="break-all">+ {t('models.model')}: {String(group.config.model)}+ </span>+ )}+ </div>+ )}+ <ModelList+ group={`${kind}-${group.mode || ''}`}+ values={credentials(group.config)}+ fallback={group.config}+ disabled={pending}+ onOrder={(values) => reorder(kind, group.mode, values)}+ onOpen={(index, readonly) =>+ open(kind, group.mode, index, readonly)+ }+ onDelete={(index) => {+ setBaseline(+ (previous) => previous ?? query.data ?? null,+ )+ setConfirm({ kind, mode: group.mode, index })+ }}+ />+ </div>+ ))}+ </section>+ )+ })}+ </TabsContent>+ </Tabs>+ {dirty && (+ <div className="sticky bottom-4 z-20 flex flex-wrap items-center justify-between gap-3 rounded-md border bg-background/95 p-3 shadow-lg backdrop-blur-sm">+ <p className="text-sm">{t('models.unsaved')}</p>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={pending}+ onClick={() => {+ setDraft(null)+ setBaseline(null)+ preview.reset()+ mutation.reset()+ setSaved(false)+ }}+ >+ <Undo2Icon />+ {t('models.discardAll')}+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={+ pending || invalidJson || query.data?.writable === false+ }+ onClick={() =>+ document && mutation.mutate({ content: document.content })+ }+ >+ <SaveIcon />+ {t(+ mutation.isPending+ ? 'models.saving'+ : preview.isPending+ ? 'models.validating'+ : 'models.saveAll',+ )}+ </Button>+ {query.data?.restart?.supported && (+ <Button+ type="button"+ size="sm"+ disabled={+ pending || invalidJson || query.data.writable === false+ }+ onClick={() =>+ document &&+ mutation.mutate({+ content: document.content,+ restart: true,+ })+ }+ >+ {t('models.saveAndRestart')}+ </Button>+ )}+ </div>+ </div>+ )}+ </div>+ <Dialog+ open={Boolean(editor)}+ onOpenChange={(isOpen) => {+ if (!isOpen && !pending) dismissEditor()+ }}+ >+ <DialogContent className="gap-0 overflow-hidden rounded-lg p-0 sm:max-w-lg">+ <DialogHeader className="border-b px-6 py-5 pr-14">+ <DialogTitle className="text-base">+ {editor ? t(titles[editor.kind]) : ''} ·{' '}+ {t(+ editor?.readonly+ ? 'models.view'+ : editor?.settings+ ? 'models.parameters'+ : 'models.edit',+ )}+ </DialogTitle>+ </DialogHeader>+ {editor && (+ <form+ className="flex min-h-0 flex-col"+ onSubmit={(event) => {+ event.preventDefault()+ applyEditor()+ }}+ >+ <div className="grid max-h-[calc(100dvh-14rem)] gap-5 overflow-y-auto px-6 py-5">+ {preview.isError && (+ <p+ role="alert"+ className="break-all text-sm text-destructive"+ >+ {t('models.validateFailed')} {preview.error.message}+ </p>+ )}+ <ModelFields+ key={`${editor.kind}-${editor.mode}-${editor.index}-${editor.settings}`}+ fields={fields}+ value={editor.value}+ inheritedModel={+ editor.settings+ ? undefined+ : (editor.mode+ ? object(current(editor.kind)[editor.mode])+ : current(editor.kind)+ ).model+ }+ readOnly={editor.readonly || pending}+ onChange={(value) => {+ if (pending) return+ if (value.provider !== editor.value.provider) {+ for (const key of [+ 'api_key',+ 'ak',+ 'sk',+ 'api_base',+ 'api_version',+ 'host',+ 'region',+ 'extra_headers',+ 'extra_request_body',+ ]) {+ value[key] = null+ }+ }+ setEditor({ ...editor, value })+ }}+ />+ {editor.kind === 'embedding' && editor.settings && (+ <>+ <p className="text-xs text-muted-foreground">+ {t('models.embeddingContract')}+ </p>+ <ModelFields+ fields={[+ { key: 'text_source' },+ { key: 'max_input_tokens', type: 'number' },+ ]}+ value={editor.value}+ readOnly+ onChange={() => {}}+ prefix="embedding-contract"+ />+ {embeddingModes+ .filter((mode) => editor.value[mode])+ .map((mode) => (+ <fieldset+ key={mode}+ className="grid gap-4 border-t pt-4"+ >+ <legend className="text-sm">+ {t(`models.${mode}`)}+ </legend>+ <ModelFields+ prefix={`${mode}-contract`}+ fields={[+ { key: 'model' },+ { key: 'dimension', type: 'number' },+ { key: 'input' },+ { key: 'query_param' },+ { key: 'document_param' },+ { key: 'version' },+ ]}+ value={object(editor.value[mode])}+ readOnly+ onChange={() => {}}+ />+ <ModelFields+ prefix={mode}+ fields={[+ {+ key: 'failback_timeout_seconds',+ type: 'number',+ min: 0.001,+ },+ {+ key: 'failback_request_count',+ type: 'number',+ min: 1,+ },+ ]}+ value={object(editor.value[mode])}+ readOnly={pending}+ onChange={(value) => {+ if (pending) return+ setEditor({+ ...editor,+ value: { ...editor.value, [mode]: value },+ })+ }}+ />+ </fieldset>+ ))}+ </>+ )}+ {!editor.settings && editor.kind === 'embedding' && (+ <details>+ <summary className="cursor-pointer text-sm text-muted-foreground">+ {t('models.advanced')}+ </summary>+ <div className="mt-4 grid gap-4">+ <ModelFields+ key={provider}+ fields={[{ key: 'extra_headers', type: 'json' }]}+ value={editor.value}+ readOnly={editor.readonly || pending}+ onChange={(value) => {+ if (!pending) setEditor({ ...editor, value })+ }}+ />+ </div>+ </details>+ )}+ </div>+ <DialogFooter className="flex-row justify-end border-t bg-muted/20 px-6 py-4">+ <Button+ type="button"+ variant="outline"+ disabled={pending}+ onClick={dismissEditor}+ >+ {t(editor.readonly ? 'models.close' : 'models.dismiss')}+ </Button>+ {editor.readonly ? (+ <Button+ type="button"+ disabled={pending}+ onClick={(event) => {+ event.preventDefault()+ if (pending) return+ setBaseline((previous) => previous ?? query.data ?? null)+ setEditor({ ...editor, readonly: false })+ }}+ >+ <PencilIcon />+ {t('models.edit')}+ </Button>+ ) : (+ <Button type="submit" disabled={pending}>+ {t('models.apply')}+ </Button>+ )}+ </DialogFooter>+ </form>+ )}+ </DialogContent>+ </Dialog>+ <Dialog+ open={Boolean(confirm)}+ onOpenChange={(isOpen) => {+ if (!isOpen) dismissConfirmation()+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('models.confirmRemove')}</DialogTitle>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="outline"+ disabled={pending}+ onClick={dismissConfirmation}+ >+ {t('models.dismiss')}+ </Button>+ <Button+ variant="destructive"+ disabled={pending}+ onClick={confirmAction}+ >+ {t('models.remove')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </TooltipProvider>+ )+}diff --git a/web-studio/src/routes/settings/-lib/config-file-api.test.ts b/web-studio/src/routes/settings/-lib/config-file-api.test.tsnew file mode 100644index 000000000..2435f67bb--- /dev/null+++ b/web-studio/src/routes/settings/-lib/config-file-api.test.ts@@ -0,0 +1,182 @@+import axios from 'axios'+import { afterEach, expect, it, vi } from 'vitest'+import {+ createConfigFileApi,+ embeddingPatch,+ isConfigFileObject,+} from './config-file-api'+import type { InternalAxiosRequestConfig } from 'axios'++afterEach(() => vi.restoreAllMocks())+it('sends only editable embedding fields and retains credential extensions supported by the account schema', () => {+ expect(+ embeddingPatch({+ max_retries: 4,+ max_input_tokens: 1000,+ text_source: 'content_only',+ dense: {+ model: 'frozen',+ dimension: 1024,+ input: 'text',+ api_key: 'parent-key',+ failback_request_count: 7,+ credentials: [+ {+ provider: 'azure',+ api_key: 'key',+ model: 'deployment',+ api_version: 'v1',+ extra_headers: { keep: 'yes' },+ dimension: 2048,+ },+ ],+ },+ }),+ ).toEqual({+ max_retries: 4,+ dense: {+ failback_request_count: 7,+ credentials: [+ {+ provider: 'azure',+ api_key: 'key',+ model: 'deployment',+ api_version: 'v1',+ extra_headers: { keep: 'yes' },+ },+ ],+ },+ })+})+it('uses ROOT credentials to preview a full draft without saving, then saves one full revision', async () => {+ const requests: InternalAxiosRequestConfig[] = []+ vi.spyOn(axios, 'create').mockReturnValue(+ axios.create({+ adapter: async (config) => {+ requests.push(config)+ return {+ status: 200,+ statusText: 'OK',+ headers: {},+ config,+ data: {+ status: 'ok',+ result: {+ revision: 'file-revision',+ content: '{"server":{"port":1933}}',+ models: Object.fromEntries(+ ['vlm', 'embedding'].map((kind) => [kind, { config: {} }]),+ ),+ },+ },+ }+ },+ }),+ )+ const api = createConfigFileApi(+ {+ baseUrl: 'http://localhost:1933',+ accountId: 'default',+ userId: 'default',+ adminApiKey: 'root-key',+ apiKey: 'user-key',+ },+ false,+ )+ const loaded = await api.get()+ const draft = await api.preview(loaded.content, {+ embedding: { max_retries: 2 },+ })+ await api.save(draft.content, loaded.revision)+ expect(+ requests.every(+ (request) => request.headers.get('X-API-Key') === 'root-key',+ ),+ ).toBe(true)+ expect(requests[0].url).toContain('source=file')+ expect(requests[0].url).not.toContain('/accounts/')+ expect(requests[1].method).toBe('patch')+ expect(requests[1].url).toContain('/api/v1/admin/configuration?source=file')+ expect(requests[1].url).toContain('dry_run=true')+ expect(JSON.parse(requests[1].data)).toEqual({+ content: loaded.content,+ settings: { embedding: { max_retries: 2 } },+ })+ expect(requests).toHaveLength(3)+ expect(requests[2].method).toBe('patch')+ expect(requests[2].url).toContain('/admin/configuration?source=file')+ expect(JSON.parse(requests[2].data)).toEqual({+ revision: 'file-revision',+ content: loaded.content,+ })+ await api.restart(loaded.revision)+ expect(requests[3].url).toBe('http://localhost:1933/api/v1/admin/restart')+ expect(requests[3].method).toBe('post')+ expect(JSON.parse(requests[3].data)).toEqual({ revision: 'file-revision' })+ expect(+ requests+ .slice(3)+ .every((request) => request.headers.get('X-API-Key') === 'root-key'),+ ).toBe(true)+})++it.each([+ ['{"port":${PORT},"enabled":$ENABLED,"nested":${OBJECT}}', true],+ [JSON.stringify({ port: '${PORT}', escaped: 'a"${KEY}' }), true],+ ['{"port":${PORT}} trailing', false],+ ['{"port":${PORT}', false],+ ['[${PORT}]', false],+ ['null', false],+])('checks startup-file object syntax for %s', async (content, valid) => {+ expect(isConfigFileObject(content)).toBe(valid)+})+it('waits for a different instance and tolerates temporary connection failures', async () => {+ const { waitForServerRestart } = await import('./config-file-api')+ vi.useFakeTimers()+ try {+ const status = vi+ .fn()+ .mockResolvedValueOnce({+ restart: { instance_id: 'old', restarting: false },+ })+ .mockRejectedValueOnce(new Error('connection refused'))+ .mockResolvedValueOnce({+ restart: { instance_id: 'new', restarting: false },+ })+ const wait = waitForServerRestart(+ status,+ 'old',+ new AbortController().signal,+ )+ await vi.advanceTimersByTimeAsync(2000)+ await wait+ expect(status).toHaveBeenCalledTimes(3)+ } finally {+ vi.useRealTimers()+ }+})+it('does not report success when the original instance stays reachable', async () => {+ const { waitForServerRestart } = await import('./config-file-api')+ vi.useFakeTimers()+ try {+ const status = vi+ .fn()+ .mockResolvedValue({ restart: { instance_id: 'old', restarting: false } })+ const result = waitForServerRestart(+ status,+ 'old',+ new AbortController().signal,+ 2000,+ ).catch((error) => error)+ await vi.advanceTimersByTimeAsync(2000)+ expect((await result).message).toBe('Restart timed out')+ } finally {+ vi.useRealTimers()+ }+})++it('accepts a verbatim file draft with a UTF-8 BOM', () => {+ expect(isConfigFileObject('\ufeff{"server":{"port":${STUDIO_PORT}}}')).toBe(+ true,+ )+})diff --git a/web-studio/src/routes/settings/-lib/config-file-api.ts b/web-studio/src/routes/settings/-lib/config-file-api.tsnew file mode 100644index 000000000..05f014b26--- /dev/null+++ b/web-studio/src/routes/settings/-lib/config-file-api.ts@@ -0,0 +1,195 @@+import { createOvClient, getOvResult, OvClientError } from '#/lib/ov-client'+import type { ConnectionDraft } from '#/hooks/use-app-connection'++export const modelKinds = ['vlm', 'embedding'] as const+export type ModelKind = (typeof modelKinds)[number]+export type ModelConfig = Record<string, unknown>+export type ModelChanges = Partial<Record<ModelKind, ModelConfig>>+export type ModelEntry = {+ config: ModelConfig+}+export type ConfigFileDraft = {+ content: string+ form_readonly?: boolean+ models: Record<ModelKind, ModelEntry>+}+export type ConfigFileConfiguration = ConfigFileDraft & {+ revision: string+ file_path?: string+ writable?: boolean+ restart_required?: boolean+ restart?: RestartStatus+ overrides?: { cluster: string[]; account: string[] }+}+export type RestartStatus = {+ supported: boolean+ instance_id: string+ restarting: boolean+ rolled_back?: boolean+}+export async function waitForServerRestart(+ load: () => Promise<ConfigFileConfiguration>,+ instanceId: string,+ signal: AbortSignal,+ timeoutMs = 120_000,+) {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ signal.throwIfAborted()+ try {+ const result = await load()+ signal.throwIfAborted()+ if (+ result.restart &&+ result.restart.instance_id !== instanceId &&+ !result.restart.restarting+ )+ return result+ } catch (error) {+ signal.throwIfAborted()+ if (+ error instanceof OvClientError &&+ (error.statusCode === 401 || error.statusCode === 403)+ )+ throw error+ // Temporary connection errors are expected during graceful shutdown.+ }+ await new Promise((resolve) => setTimeout(resolve, 1000))+ }+ throw new Error('Restart timed out')+}+export const embeddingModes = ['dense', 'sparse', 'hybrid'] as const+export const embeddingCredentialFields = [+ 'id',+ 'provider',+ 'model',+ 'api_key',+ 'api_base',+ 'api_version',+ 'ak',+ 'sk',+ 'region',+ 'host',+ 'extra_headers',+]++export function isConfigFileObject(content: string): boolean {+ try {+ // Startup expands unquoted environment values before parsing JSON.+ // Only check their syntax here; the server owns expansion and validation.+ const parsed: unknown = JSON.parse(+ content+ .trimStart()+ .replace(/"(?:[^"\\]|\\.)*"|\$(?:\{[^}]*\}|[a-zA-Z0-9_]+)/g, (token) =>+ token.startsWith('"') ? token : JSON.stringify(token),+ ),+ )+ return (+ parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)+ )+ } catch {+ return false+ }+}++export function object(value: unknown): ModelConfig {+ return value && typeof value === 'object' && !Array.isArray(value)+ ? (value as ModelConfig)+ : {}+}+export function credentials(config: ModelConfig): ModelConfig[] {+ return Array.isArray(config.credentials) ? config.credentials.map(object) : []+}+export function embeddingPatch(config: ModelConfig): ModelConfig {+ const patch: ModelConfig = {}+ for (const key of ['max_retries', 'max_concurrent', 'circuit_breaker']) {+ if (config[key] !== undefined) patch[key] = config[key]+ }+ for (const mode of embeddingModes) {+ if (!config[mode]) continue+ const section = object(config[mode])+ patch[mode] = {+ credentials: credentials(section).map((credential) =>+ Object.fromEntries(+ Object.entries(credential).filter(([key]) =>+ embeddingCredentialFields.includes(key),+ ),+ ),+ ),+ ...Object.fromEntries(+ ['failback_timeout_seconds', 'failback_request_count']+ .filter((key) => section[key] !== undefined)+ .map((key) => [key, section[key]]),+ ),+ }+ }+ return patch+}++export function createConfigFileApi(+ connection: ConnectionDraft,+ trusted: boolean,+) {+ const { client } = createOvClient({+ baseUrl: connection.baseUrl,+ connection: { ...connection, identityHeaders: trusted },+ })+ const url = '/api/v1/admin/configuration'+ return {+ restart: (revision: string) =>+ getOvResult<RestartStatus>(+ client.post({+ url: '/api/v1/admin/restart',+ headers: { 'Content-Type': 'application/json' },+ body: { revision },+ }),+ ),+ get: async (timeout = 0) => {+ const result = await getOvResult<+ Omit<ConfigFileConfiguration, 'models'> & {+ models?: Partial<ConfigFileConfiguration['models']>+ }+ >(+ client.get({+ url,+ timeout,+ query: { source: 'file', account_id: connection.accountId },+ }),+ )+ const models = result.models+ if (+ typeof result.content !== 'string' ||+ !models ||+ modelKinds.some((kind) => !models[kind])+ )+ throw new Error('Model configuration response is unavailable')+ return { ...result, models: models as ConfigFileConfiguration['models'] }+ },+ preview: (content: string, changes: ModelChanges = {}) =>+ getOvResult<ConfigFileDraft>(+ client.patch({+ url,+ query: { source: 'file', dry_run: true },+ headers: { 'Content-Type': 'application/json' },+ body: {+ content,+ settings: Object.fromEntries(+ Object.entries(changes).map(([kind, config]) => [+ kind,+ kind === 'embedding' ? embeddingPatch(config) : config,+ ]),+ ),+ },+ }),+ ),+ save: (content: string, revision: string) =>+ getOvResult<{ revision: string; restart_required: boolean }>(+ client.patch({+ url,+ query: { source: 'file' },+ headers: { 'Content-Type': 'application/json' },+ body: { revision, content },+ }),+ ),+ }+}diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsxindex df59ba226..2434f77ef 100644--- a/web-studio/src/routes/settings/route.tsx+++ b/web-studio/src/routes/settings/route.tsx@@ -30,11 +30,37 @@ import { PLAIN_INPUT_PROPS } from '#/lib/form-input'import { cn } from '#/lib/utils'import { localizeCapabilityDetail } from './-lib/localize-capability-probe'import type { ConnectionDraft } from '#/hooks/use-app-connection'+import { Tabs, TabsContent, TabsList, TabsTrigger } from '#/components/ui/tabs'+import { ServerConfigurationEditor } from './-components/server-configuration'export const Route = createFileRoute('/settings')({component: ConnectionSettingsRoute,})+function ConnectionSettingsRoute() {+ const { t } = useTranslation('settings')+ const { identityScopeKey } = useAppConnection()+ return (+ <div className="flex w-full min-w-0 flex-col gap-5">+ <h1 className="text-2xl font-semibold">{t('pageTitle')}</h1>+ <Tabs defaultValue="connection" className="min-w-0 gap-5">+ <TabsList variant="line">+ <TabsTrigger value="connection">{t('tabs.connection')}</TabsTrigger>+ <TabsTrigger value="configuration">+ {t('tabs.configuration')}+ </TabsTrigger>+ </TabsList>+ <TabsContent value="connection">+ <ConnectionSettingsPanel />+ </TabsContent>+ <TabsContent value="configuration" keepMounted>+ <ServerConfigurationEditor key={identityScopeKey} />+ </TabsContent>+ </Tabs>+ </div>+ )+}+function getCapabilityIcon(result: CapabilityProbeResult | undefined) {if (!result) {return <CircleDashedIcon className="size-4" />@@ -124,7 +150,7 @@ function UserApiKeyInput({)}-function ConnectionSettingsRoute() {+function ConnectionSettingsPanel() {const { i18n, t } = useTranslation('settings')const { connection, saveConnection, serverMode } = useAppConnection()const [draft, setDraft] = React.useState<ConnectionDraft>(connection)@@ -241,15 +267,6 @@ function ConnectionSettingsRoute() {return (<div className="flex w-full min-w-0 flex-col gap-5">- <header className="flex flex-col gap-2">- <h1 className="text-2xl font-semibold tracking-tight">- {t('connectionPage.title')}- </h1>- <p className="max-w-3xl text-sm leading-6 text-muted-foreground">- {t('connectionPage.description')}- </p>- </header>-<Card className="gap-0 overflow-hidden border-primary/25 bg-primary/[0.025] py-0 shadow-sm ring-1 ring-primary/10"><CardHeader className="gap-2 border-b border-primary/15 bg-primary/[0.07] px-5 py-3.5"><div className="flex flex-wrap items-center justify-between gap-2">