"""Runtime settings store: validated read/update/persist for editable knobs. The Settings page must be able to save Browser / HITL knobs for real. Two mechanisms combine: 1. **Live mutation** — the `settings` singleton (config.py) is the same object the browser manager reads at *session-creation* time, so setting an attribute applies to every new browser session without a backend restart. 2. **Persistence** — pydantic-settings loads `.env` from the working directory at startup (`env_file=".env"`, and the `init` command writes the same file), so rewriting the relevant `KEY=value` lines in `.env` makes a saved value survive backend restarts. Editable fields are explicitly whitelisted below — secrets (API keys, LLM keys) are never reachable through this API. """ from pathlib import Path from typing import Any from .config import settings from .env_file import ensure_parent, resolve_env_file # ── Editable-field contract ────────────────────────────────────────────────── # field name on Settings -> spec. `kind` drives validation; ints are clamped # into [min, max] so a typo can't wedge the agent with an unusable value. # # `browser_channel` accepts every channel the browser manager can launch # (browser/manager.py SUPPORTED_CHANNELS). It used to accept only # chromium/firefox/webkit, so the UI's "Google Chrome" and "Microsoft Edge" # options were rejected with HTTP 400 while the manager happily launched them — # the Settings page and the engine picker disagreed about the same contract. EDITABLE_SETTINGS: dict[str, dict[str, Any]] = { "browser_headless": {"kind": "bool"}, "browser_timeout": {"kind": "int", "min": 1000, "max": 600_000}, "browser_channel": { "kind": "choice", "choices": ("chromium", "chrome", "msedge", "firefox", "webkit"), }, "hitl_timeout": {"kind": "int", "min": 10, "max": 86_400}, "enable_native_messaging": {"kind": "bool"}, } # Read-only facts the Settings UI displays next to the editable knobs. READ_ONLY_SETTINGS = ("host", "port") def _env_key(field: str) -> str: """Settings field name -> canonical UPPER_SNAKE .env key (pydantic-settings matches keys case-insensitively, so this is the canonical spelling).""" return field.upper() class SettingsValidationError(ValueError): """A posted value failed validation; carries the offending field.""" def read_settings() -> dict[str, Any]: """Effective editable + read-only values, safe for the frontend (no secrets).""" out: dict[str, Any] = {f: getattr(settings, f) for f in EDITABLE_SETTINGS} out.update({f: getattr(settings, f) for f in READ_ONLY_SETTINGS}) return out def _validate(field: str, spec: dict[str, Any], raw: Any) -> Any: """Validate/coerce one posted value. Raises SettingsValidationError.""" kind = spec["kind"] if kind == "bool": if isinstance(raw, bool): return raw if isinstance(raw, str) and raw.strip().lower() in {"true", "1", "yes", "on"}: return True if isinstance(raw, str) and raw.strip().lower() in {"false", "0", "no", "off"}: return False raise SettingsValidationError(f"{field} must be true or false") if kind == "int": try: value = int(raw) except (TypeError, ValueError): raise SettingsValidationError(f"{field} must be an integer") from None return max(spec["min"], min(spec["max"], value)) if kind == "choice": if isinstance(raw, str) and raw in spec["choices"]: return raw raise SettingsValidationError( f"{field} must be one of: {', '.join(spec['choices'])}" ) raise SettingsValidationError(f"{field} has an unknown validation kind ({kind})") def _env_value(value: Any) -> str: """Serialize a Python value for a `KEY=value` .env line — booleans in the lowercase form the `init` command writes (`str(False)` would emit `False`).""" if isinstance(value, bool): return str(value).lower() return str(value) def _persist_env_values(updates: dict[str, str]) -> Path: """Write KEY=value pairs into the settings file pydantic-settings loads at startup (the same file `config.py` reads — see `env_file.py`). Existing lines for a key are replaced in place — comments and unrelated keys are preserved; new keys are appended under a marker comment. Returns the file path written.""" env_path = resolve_env_file() ensure_parent(env_path) lines: list[str] = [] if env_path.exists(): lines = env_path.read_text(encoding="utf-8").splitlines() wanted = {_env_key(field): _env_value(value) for field, value in updates.items()} seen: set[str] = set() out: list[str] = [] for line in lines: stripped = line.strip() if "=" in stripped and not stripped.startswith("#"): key = stripped.split("=", 1)[0].strip().upper() if key in wanted: out.append(f"{key}={wanted[key]}") seen.add(key) continue out.append(line) missing = [f"{key}={value}" for key, value in wanted.items() if key not in seen] if missing: if out and out[-1].strip(): out.append("") out.append("# Saved from the Settings UI") out.extend(missing) env_path.write_text("\n".join(out) + "\n", encoding="utf-8") return env_path def apply_updates(payload: Any) -> dict[str, Any]: """Validate a posted settings payload, mutate the live singleton, persist to `.env`. Unknown fields are ignored (forward compatibility). Returns the handler response body.""" if not isinstance(payload, dict): raise SettingsValidationError("body must be a JSON object") validated: dict[str, Any] = {} ignored: list[str] = [] for field, raw in payload.items(): spec = EDITABLE_SETTINGS.get(field) if spec is None: ignored.append(field) continue validated[field] = _validate(field, spec, raw) # Mutate only after every value validated — a bad field must not half-apply. for field, value in validated.items(): setattr(settings, field, value) env_path: Path | None = None if validated: env_path = _persist_env_values(validated) # Flat echo: settings fields at the top level (same shape as GET) so the # frontend can adopt the response directly as its new form state. return { **read_settings(), "updated": sorted(validated), "ignored": sorted(ignored), "env_file": str(env_path) if env_path else None, "note": "Applied to the running backend; browser headless/timeout/channel take effect for new sessions.", }