File size: 7,044 Bytes
6eb6c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""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.",
    }